【问题标题】:Returning pointer to class member - should I avoid it?返回指向类成员的指针 - 我应该避免它吗?
【发布时间】:2016-03-06 22:00:55
【问题描述】:

我没有编程经验,所以想问问你的意见。例如我有 3 个类:

class A
{
public:
   A(int size);
   int getSize();
private:
   int size_;
};

class B
{
public:
   A* getChild(int childNumber);
   int getNChildren()
   {
      return children.size();
   }
private:
   std::vector<A> children;
};

class C
{
public:
   void sumSize()
   {
       int sum = 0;
       for(int i = 0; i < member.getNChildren(); i++)
       {
            sum += member.getChild(i)->getSize(); // here I wonder if this is good style
       }
   }

private:
  B member;
};

这是一种不好的做法吗?我知道我可以在 B 类中有方法 sumSize() 并返回这个总和,但是我可以这样做还是在更大的程序中会有并发症? 所以这是我的主要问题:

  1. 我是否应该避免返回指向成员的指针:A* getChild(int childNumber);
  2. 所有涉及儿童的东西都应该是计算的 B班?

【问题讨论】:

  • 为什么是指针而不是引用?
  • 这只是一个例子,在我的程序中我需要多态
  • operator 是 C++ 中的一个关键字...该代码甚至编译了吗??
  • @user3191398 多态性也适用于引用。您的 getChild 几乎与规范的 operator[] 一样工作,除了返回对元素的引用。
  • 如果A 是多态基类并且您希望能够存储派生对象,则不能使用vector&lt;A&gt;

标签: c++ oop coding-style


【解决方案1】:

我相信您正在描述一种容器设计模式,这种模式备受推崇且非常有用。作为设计者,如果您决定成员函数是公开的,那么您打算让“外部世界”访问它们,而该决定取决于您要完成的任务。

也许你不希望外界修改这个成员,所以也许const A* getChild(int childNumber) 可能就是你想要的。

在设计时考虑“const-ness”是一个好习惯,示例中的所有三个公共成员函数都可以是 const(例如 int getSize() const),而不会影响您演示的功能。

这里的一个错误是使用operator 作为私有数据成员的名称。 operator 是 C++ 中的保留关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2013-06-27
    • 2018-03-24
    • 2015-05-20
    • 2015-11-12
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多