简体   繁体   中英

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
{
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 :

void Print(const A& a)
{
  cout << a.b.x;
}

A read function should set the values of a (and b ) and their members:

void Read(A& a)
{ 
  // ...
  a.b.x = 2;
}

How should class A be implement regarding its member access?

  • Should " b " be public?
  • Should " class A " provide 2 getters for b (1 for write and 1 read access to "b")?

Additional information:
In my real system the classes A and B are much larger and they are part of a huge legacy system. 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 . So the resposibility of A and B is to hold the data (some kind of data models).

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 :

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 . You could then build a function in class A :

void setX(int x)
{
    b = x;
}

Finally though, for your printing, the idiomatic way is to overload << for std::ostream . Then you can remove your Print functions. See How to properly overload the << operator for an ostream? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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