如果可以像这样组合它们,为什么需要单独的 get 和 set 函数:
class A {
private:
int var = 0;
public:
int& getset(){ return var; };
};
int main()
{
A a = A();
a.getset() = 4;
std::cout << "Hello, " << a.getset() << "!\n";
}
我假设我忽略了一些东西,但万一这不是一个好主意;为什么可以通过这种方式访问私有(private)成员?
最佳答案
根本不需要 getter 和 setter:只需将变量公开即可。
class A {
public:
int var = 0;
};
如果您想隐藏实现细节,那么想法是 getter 是 const
而 setter 不是。所以他们一定是不同的函数
class A{
public:
int getValue() const;
int setValue(int new_value); // returns old value
private:
/* implementation details: Value may be encoded other than in a simple variable */
};
关于c++ - 使用 getter 设置私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44019529/