<分区>
我对 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;
}
不确定我是否以简单的方式解释了我的担忧。 预先感谢您的回复和帮助。