简体   繁体   English

在C ++中使用const引用参数访问函数中成员的最佳实践

[英]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 &参数,应打印的成员ab

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

  • Should " b " be public? b应该公开吗?
  • Should " 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. 在我的真实系统中,类AB更大,它们是庞大的旧系统的一部分。 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 . 在该传统系统PrintRead是一个“视图模型”,其中的成员函数Print的值写入到GUI和Read读取来自GUI的值,并设置的成员AB So the resposibility of A and B is to hold the data (some kind of data models). 因此, AB的责任在于保存数据(某种数据模型)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM