c++中类中私有成员的调用?
天蓬老师
天蓬老师 2017-04-17 13:42:40
[C++讨论组]
#include <iostream>
using namespace std;
class test{
      private:
            int a;
            int b;
      public:
            test(int a = 1, int b = 2){
                  this->a = a;
                  this->b = b;
            }
            int re(test ccc){
                  a = ccc.a + 444;
                  b = ccc.b + 444;
            }
};

为什么re函数中的ccc可以直接调用a和b而不报错?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(8)
怪我咯

搜了下(关键字: c++ access class private variable),这里有不错的解释:

http://stackoverflow.com/questions/7396846/with-a-private-modifier-why-can-the-member-in-other-objects-be-accessed-directl

Good question. The point is that protection in C++ is class level, not object level. So a method being invoked on one object can access private members of any other instance of the same class.

This makes sense if you see the role of protection being to allow encapsulation to ensure that the writer of a class can build a cohesive class, and not have to protect against external code modifying object contents.

Another thought as to the real "why?". Consider how you write almost any copy constructor; you want access to the original's underlying data structure, not its presented interface.

PHP中文网

因为 C++ 中一个类是自己这个类的友元(friend class)。

高洛峰

因为 a,b 都是 test 类的成员。

阿神

一个类的方法可以访问自己的私有成员

迷茫

同一类的不同对象间可以互相访问私有成员

PHP中文网

一个类里当然可以

PHP中文网

私有数据不能被直接访问,只能通过类的成员函数和友元函数调用。

大家讲道理

友元函数 http://learn.jser.com/cplusplus/cpp-friend-functions.html

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号