C++ getters/setters coding style

前端 未结 8 1472
小蘑菇
小蘑菇 2020-11-27 10:41

I have been programming in C# for a while and now I want to brush up on my C++ skills.

Having the class:

class Foo
{
    const std::string& name         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 11:40

    As an aside, in C++, it is somewhat odd to have a const reference member. You have to assign it in the constructor list. Who owns the actually memory of that object and what is it's lifetime?

    As for style, I agree with the others that you don't want to expose your privates. :-) I like this pattern for setters/getters

    class Foo
    {
    public:
      const string& FirstName() const;
      Foo& FirstName(const string& newFirstName);
    
      const string& LastName() const;
      Foo& LastName(const string& newLastName);
    
      const string& Title() const;
      Foo& Title(const string& newTitle);
    };
    

    This way you can do something like:

    Foo f;
    f.FirstName("Jim").LastName("Bob").Title("Programmer");
    

提交回复
热议问题