我有這個類聲明。我觀察到在方法距離(點b)中,如何訪問Point-b.x和b.y的私有成員?如果我嘗試訪問main中的b.x和b.y,則不允許。爲什麼在這裏訪問私有變量?
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
int x, y;
public:
Point() {
cout << "Constructor called" << endl;
x = 0; y = 0;
}
~Point() {
}
void set(int a, int b) {
x = a;
y = b;
}
void offset(int dx, int dy) {
x += dx;
y += dy;
}
void print() {
cout << "(" << x << "," << y << ")" << endl;
}
// HERE
double distance(Point b) {
return (sqrt(pow(x-b.x, 2)+pow(y-b.y, 2)));
}
};
int main() {
Point p, q;
p.print();
p.offset(4, 3);
p.print();
q.set(10, 2);
cout << "Distance: " << p.distance(q) << endl;
return 0;
}
注:我已經編譯和運行在ideone.com
因爲距離'是'Point'的成員。 – chris
如果類成員函數無法訪問私有變量,可能會發生什麼? –
[什麼是訪問說明符?我應該繼承與私人,保護或公共?](http://stackoverflow.com/questions/5447498/what-are-access-specifiers-should-i-inherit-with-private-protected-or-public) –