[英]Best practices accessing members in function with const reference parameter in C++
What is the best practice to implement following scenario: 实施以下方案的最佳实践是什么:
Class A
holds a member object of Type B
. Class A
拥有类型B
的成员对象。
class A
{
private:
B b;
};
class B
{
private:
int x;
};
A print function which gets an object of type A
as const &
parameter, should print the members of a
and b
: 它获取类型的对象的打印功能
A
作为const &
参数,应打印的成员a
和b
:
void Print(const A& a)
{
cout << a.b.x;
}
A read function should set the values of a
(and b
) and their members: 读取函数应设置
a
(和b
)及其成员的值:
void Read(A& a)
{
// ...
a.b.x = 2;
}
How should class A
be implement regarding its member access? 关于其成员访问权限,应如何实施
class A
?
b
" be public? b
应该公开吗? class A
" provide 2 getters for b (1 for write and 1 read access to "b")? class A
”是否应该为b提供2个吸气剂(1个对“ b”的写访问和1个读访问)? Additional information: 附加信息:
In my real system the classes A
and B
are much larger and they are part of a huge legacy system. 在我的真实系统中,类
A
和B
更大,它们是庞大的旧系统的一部分。 In this legacy system Print
and Read
are member functions of a "View-Model", where Print
writes the values to the GUI and Read
reads the values from the GUI and sets the members of A
and B
. 在该传统系统
Print
和Read
是一个“视图模型”,其中的成员函数Print
的值写入到GUI和Read
读取来自GUI的值,并设置的成员A
和B
。 So the resposibility of A
and B
is to hold the data (some kind of data models). 因此,
A
和B
的责任在于保存数据(某种数据模型)。
You ought to use member functions instead, and keep the data as encapsulated as possible. 您应该改用成员函数,并尽可能地封装数据。 To that end,
Print
could be a member function of A
: 为此,
Print
可以是A
的成员函数:
class A
{
B b;
public:
void Print() const /*Let's add some const correctness*/
{
b.Print();
}
};
and 和
class B
{
int x;
public:
void Print() const
{
std::cout << x;
}
B& operator=(int new_x) /*Standard form of the assignment operator*/
{
x = new_x;
return *this;
}
};
Note that I've provided an assigment operator for B
. 请注意,我为
B
提供了赋值运算符 。 You could then build a function in class A
: 然后,您可以在
A
类中构建一个函数:
void setX(int x)
{
b = x;
}
Finally though, for your printing, the idiomatic way is to overload <<
for std::ostream
. 最后,尽管如此,对于您的打印,惯用的方法是为
<<
std::ostream
重载<<
。 Then you can remove your Print
functions. 然后,您可以删除
Print
功能。 See How to properly overload the << operator for an ostream? 请参阅如何为ostream适当地重载<<操作符? .
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.