【发布时间】: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() 并返回这个总和,但是我可以这样做还是在更大的程序中会有并发症? 所以这是我的主要问题:
- 我是否应该避免返回指向成员的指针:
A* getChild(int childNumber); - 所有涉及儿童的东西都应该是计算的 B班?
【问题讨论】:
-
为什么是指针而不是引用?
-
这只是一个例子,在我的程序中我需要多态
-
operator是 C++ 中的一个关键字...该代码甚至编译了吗?? -
@user3191398 多态性也适用于引用。您的
getChild几乎与规范的operator[]一样工作,除了返回对元素的引用。 -
如果
A是多态基类并且您希望能够存储派生对象,则不能使用vector<A>
标签: c++ oop coding-style