C ++:复制构造函数:是直接使用getter还是访问成员var? [英] C++: Copy constructor: Use getters or access member vars directly?

查看:104
本文介绍了C ++:复制构造函数:是直接使用getter还是访问成员var?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有复制构造函数的简单容器类。

I have a simple container class with a copy constructor.

您是否建议使用getter和setter或直接访问成员变量?

Do you recommend using getters and setters, or accessing the member variables directly?

public Container 
{
   public:
   Container() {}

   Container(const Container& cont)          //option 1
   { 
       SetMyString(cont.GetMyString());
   }

   //OR

   Container(const Container& cont)          //option 2
   {
      m_str1 = cont.m_str1;
   }

   public string GetMyString() { return m_str1;}       

   public void SetMyString(string str) { m_str1 = str;}

   private:

   string m_str1;
}




  • 在此示例中,所有代码都是内联的,但是在我们的真实代码中没有内联代码。

  • 更新(09年9月29日):

    其中一些答案写得很好,但是似乎似乎遗漏了这个问题的重点:

    Some of these answers are well written however they seem to get missing the point of this question:


    • 这很简单讨论使用getters / setters与变量的示例

    • this is simple contrived example to discuss using getters/setters vs variables

    初始化器列表或私有验证器函数并不是这个问题的真正组成部分。我想知道这两种设计是否会使代码易于维护和扩展。

    initializer lists or private validator functions are not really part of this question. I'm wondering if either design will make the code easier to maintain and expand.

    在此示例中,某些ppl专注于字符串,但这只是一个示例,请想象它是一个不同的对象。

    Some ppl are focusing on the string in this example however it is just an example, imagine it is a different object instead.

    我不关心性能。我们不是在PDP-11上编程

    I'm not concerned about performance. we're not programming on the PDP-11

    推荐答案

    如何返回字符串,例如。修剪空白,是否检查为null等?与SetMyString()相同,如果答案是肯定的,则最好使用访问方法,因为您不必在成千上万的地方更改代码,而只需修改这些getter和setter方法。

    Do you anticipate how the string is returned, eg. white space trimmed, null checked, etc.? Same with SetMyString(), if the answer is yes, you are better off with access methods since you don't have to change your code in zillion places but just modify those getter and setter methods.

    这篇关于C ++:复制构造函数:是直接使用getter还是访问成员var?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆