一个班级的私人功能可以访问?

Sta*_*rst 4 c++ oop gcc information-hiding class

我一直在努力学习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;
}
Run Code Online (Sandbox Code Playgroud)

而对于我的生活,我无法弄清楚为什么这些方法void add(Point P)void sub( Point p )工作.

"cannot access private properties of class Point"当我尝试使用add或时,我不应该得到类似的错误sub吗?

gcc版本编译的程序4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5).运行时输出:

(13, 6)
 (3, 1)
Run Code Online (Sandbox Code Playgroud)

Mat*_*tzi 7

Private关键字指定只能从类的成员函数和朋友访问这些成员.私有变量可以由相同类型的对象访问,甚至可以从该类的其他实例访问.

这与安全性并不是很多人的想法.这是关于从其他代码隐藏类的内部结构.要求一个类不会意外地弄乱其他实例,因此没有必要隐藏其他实例中的变量.(实际上实现起来会有点棘手,没有或没有理由这样做.)


vin*_*ehl 5

private除了friends 之外,不能从类外部访问成员,但可以从类的任何位置访问成员.