请问为啥成员函数sum中对象可以直接访问私有类型成员a.x

东拉西扯到天亮 2018-04-12 01:28:42
#include<iostream>

using namespace std;

class test
{
private:
    int x;
    int y;
public:
    test(int a = 0, int b = 0) :x(a), y(b) {}
    int getx()
    {
        return x;
    }
    int gety() { return y; }
    void sum(test a)
    {
        cout << this->x + a.x + a.y << endl;
    }
    friend void Sum(test &a, test &b);
};

void Sum(test &a,test &b)
{
    cout << a.x + a.y + b.x + b.y << endl;
}

int main()
{
    test t(1, 2);
    test b(3, 4);
    t.sum(b);
    Sum(t, b);
}
...全文
663 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
谢谢您的回答,解决了我的一大困惑。
gspUser 2018-04-13
  • 打赏
  • 举报
回复
https://blog.csdn.net/iaccepted/article/details/34853937 实践证明,类(class)私有成员可以被类成员函数访问,不区分成员在哪个实例(instance)里。 https://www.cnblogs.com/lgh1992314/p/6616376.html C++的访问修饰符的作用是以类为单位,而不是以对象为单位。 通俗的讲,同类的对象间可以“互相访问”对方的数据成员,只不过访问途径不是直接访问. 类体内的访问没有访问限制一说,即private函数可以访问public/protected/private成员函数或数据成员,同理,protected函数,public函数也可以任意访问该类体中定义的成员。public继承下,基类中的public和protected成员继承为该子类的public和protected成员(成员函数或数据成员),然后访问仍然按类内的无限制访问。

552

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder 茶馆
社区管理员
  • 茶馆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧