我正在学习C++中OOP的基本概念,但我遇到了一个逻辑问题.
#include <iostream>
#include <conio.h>
using namespace std;
class A {
int i;
public:
void set(int x) {
i=x;
}
int get() {
return i;
}
void cpy(A x) {
i=x.i;
}
};
int main()
{
A x, y;
x.set(10);
y.set(20);
cout << x.get() << "\t" << y.get() << endl;
x.cpy(y);
cout << x.get() << "\t" << y.get() << endl;
getch();
}
Run Code Online (Sandbox Code Playgroud)
我想在上面的代码中知道为什么我能够访问x.i
[第19行],它是不同对象中的私有成员.即使对象作为参数传递,私有范围也不限于同一个类吗?
Kon*_*lph 13
private
在C++中意味着对类是私有的,而不是对象的私有.两种解释都是可能的,实际上有些语言选择了另一种语言.但是大多数语言都像C++,并允许同一类的对象访问另一个实例的私有成员.