c++ - 可访问类的私有(private)函数?

标签 c++ oop class gcc information-hiding

一段时间以来,我一直在努力学习 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) 起作用。

当我尝试使用 addsub?

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

(13, 6)
 (3, 1)

最佳答案

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

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

关于c++ - 可访问类的私有(private)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641358/

相关文章:

c++ - 如何在保持原始索引的同时对 vector 的 vector 进行排序?

c++ - 如果字符串的开始 inc spec 值

类结构中的 PHP 内存泄漏

c++ - C++中通过引用传递类成员函数返回值

java - 错误 : Could not find or load main class org. newdawn.slick.tests.AlphaMapTest

c++ - clang++ 12 是否支持 C++20 std::construct_at?

c++ - 如何确定两个边缘图像是否应该匹配

c++ - 抵御 C++ 继承陷阱的设计技巧

swift - 是什么让 Swift 中的调用变得昂贵?

javascript - 有没有办法忽略带有 <noscript> 标签的类?