【发布时间】:2019-11-01 03:51:49
【问题描述】:
我在使用英语方面很笨拙。希望你能理解。
我们如何在没有 getter 的情况下访问私有成员?看不懂。
当我们了解 C++ 私有、公共、受保护、私有成员或函数时,可以在类范围内访问。
class TestClass {
public:
TestClass() {
testMem = 10;
}
void testFunction() {
cout << testMem << endl;
}
private:
int testMem;
}
但是,当我看到这段代码时,我真的很困惑。
class B {
public:
B() {
testNumber = 10;
}
void printMember() {
cout << testNumber << endl;
}
private:
int testNumber;
}
class Money {
public:
Money();
bool operator < (Money& amount, B& b) const {
// this code doesn't make any error
// why same type member can access their private member directly without getter and setter?
amount.cents = 10;
amount.dollors = 10;
// this Code make a error
// b.testNumber = 10;
// below
// compare code
}
private:
int dollars;
int cents;
};
我真的很困惑.. 为什么 Money& amount 参数可以在没有 getter 和 setter 的情况下访问他们的私人成员?但是 B 类不能在没有 getter 的情况下访问他们的私有成员。如何..?为什么..?
【问题讨论】:
-
私有成员被设计成类外的方法不能访问它们。隐私有助于支持松散耦合、数据隐藏和封装等概念。如果您需要从类之外的方法访问私有成员,我建议您检查您的设计。
-
此代码仅供测试! umm 相同类型的参数如何在没有 getter 的情况下直接访问其成员?
标签: c++ reference private accessor