【发布时间】:2023-03-04 01:17:02
【问题描述】:
我已经尝试学习 C++ 有一段时间了。最近我遇到了以下一段代码:
#include <iostream>
using namespace std;
class Point {
private:
double x_, y_;
public:
Point(double x, double y){
x_ = x;
y_ = y;
}
Point() {
x_ = 0.0;
y_ = 0.0;
}
double getX(){
return x_;
}
double getY(){
return y_;
}
void setX(double x){
x_ = x;
}
void setY(double y){
y_ = y;
}
void add(Point p){
x_ += p.x_;
y_ += p.y_;
}
void sub(Point p){
x_ -= p.x_;
y_ -= p.y_;
}
void mul(double a){
x_ *= a;
y_ *= a;
}
void dump(){
cout << "(" << x_ << ", " << y_ << ")" << endl;
}
};
int main(){
Point p(3, 1);
Point p1(10, 5);
p.add(p1);
p.dump();
p.sub(p1);
p.dump();
return 0;
}
对于我的一生,我无法弄清楚为什么 void add(Point P) 和 void sub( Point p ) 方法有效。
当我尝试使用add 或sub 时,我不应该收到"cannot access private properties of class Point" 之类的错误吗?
使用gcc 版本4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 编译的程序。
运行时输出:
(13, 6)
(3, 1)
【问题讨论】:
-
它是
Point类的一部分,因此它可以访问自己的私有成员。 -
不能访问自己的隐私会有多糟糕?
-
访问说明符是每个类型而不是每个实例。因此,在成员方法中,您可以访问所有私有成员,无论它们属于此实例还是其他实例。
标签: c++ oop class gcc information-hiding