Closed. This question is opinion-based。它当前不接受答案。
想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
2年前关闭。
Improve this question
我还是C++和OOP编程的新手,我只是想知道一些奇怪的事情。
我有一个让我们将其命名为
我的问题是:
实现私有(private) getter 和 setter 是错误的吗?
还是应该使用直接访问?
伪代码如下:
这个可以吗?
在主要方面:
还是我应该:
不知道我是否以简单的方式解释了我的担忧。
预先感谢您的答复和帮助。
想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
2年前关闭。
Improve this question
我还是C++和OOP编程的新手,我只是想知道一些奇怪的事情。
我有一个让我们将其命名为
Foo
的类,其中包含一些私有(private)成员。我的问题是:
Foo
对象在生命周期内不会“传递数据”给其他对象。他们接收数据,执行操作并将新数据保存到文件中。这意味着,只有Foo
对象可以访问Foo
私有(private)成员。实现私有(private) getter 和 setter 是错误的吗?
还是应该使用直接访问?
伪代码如下:
这个可以吗?
class foo
{
private:
string a;
string b;
string c;
void setA(string A){this->a=A;}
string getA()const{return this->a;
void setB(string B){this->b=B;}
string getB()const{return this->b;
void setC(string C){this->c=C;}
string getC()const{return this->b;
public:
//many omitted methods//
void Method(); //<-- this method does things and calls private getters and setters to modify private members
}
在主要方面:
{
Foo obj=....;
obj.Method();
}
还是我应该:
class foo
{
private:
string a;
string b;
string c;
public:
//many omitted methods//
void Method();
}
void foo::method()
{
string s1;
//initialize s1;
this->a=s1; //operation example
std::cout<<"A equals: "<< this->a;
}
不知道我是否以简单的方式解释了我的担忧。
预先感谢您的答复和帮助。
最佳答案
除非您以某种有趣的方式利用多态,否则编写private
“getters”和“setters”是没有意义的。
通过构造函数设置成员变量是最好的方法,并且使成员const
可以防止意外修改它们。
尽可能避免使用“setter”,无论其可访问性如何,因为它们只是绕过封装而已。