Home  >  Q&A  >  body text

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而不报错?

天蓬老师天蓬老师2713 days ago505

reply all(8)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:44:40

    搜了下(关键字: 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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:44:40

    Because a class in C++ is a friend class of its own class.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:44:40

    Because a and b are both members of the test class.

    reply
    0
  • 阿神

    阿神2017-04-17 13:44:40

    Methods of a class can access its own private members

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:44:40

    Different objects of the same class can access each other’s private members

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:44:40

    Of course it can be in a class

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:44:40

    Private data cannot be accessed directly and can only be called through member functions and friend functions of the class.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:44:40

    Friend functions http://learn.jser.com/cplusplus/cpp-friend-functions.html

    reply
    0
  • Cancelreply