【发布时间】:2015-06-18 13:43:36
【问题描述】:
我在 C++ 中的继承有一些困难。假设我有一个类基父:
class Parent{
public:
...
virtual Parent Intersection(Parent anotherParent);
}
还有 2 个子类 Numeric 和 Symbolic,实现方法 Intersection:
class Numeric : public Parent{
public:
...
Numeric Intersection(Numeric anotherNumeric)
{
...
}; // do intersection with another object numeric
}
// class Symbolic
class Symbolic : public Parent{
public:
...
symbolic Intersection(Symbolic anotherSymbolic)
{
...
}; // do intersection with another object symbolic
}
最后一个类ParentVector:
class ParentVector : public Parent{
public:
...
ParentVector Intersection(ParentVector anotherParentVector);
private:
std::vector<Parent> vtParent; // vector stock object Parent (Numeric or Symbolic)
}
我想要矢量 vtParent 存储 2 种类型的对象:数字或符号。所以我创建了一个父对象的向量。
问题是:我想得到 2 个向量 ParentVector 的交集。
我可以在向量 vtParent 中添加一个对象 Numeric 或 Symbolic 但我不能调用方法 Intersection 对应于每种类型的对象。它总是调用类Parent的方法Intersection。
有人有什么想法或建议吗?非常感谢。
//edit : 我忘记了 ParentVector 类也是 Parent 类的子类。
// 更新:感谢您提供的所有有用帮助。现在,我想执行下面的代码来计算 2 个向量 Parent 的交集:
ParentVector* Intersection(ParentVector anotherParentVector){
ParentVector* result;
Parent* tmp;
for( int i = 0; i < this->vtParent.size(i); i++ ){
// PROBLEM with this line because I don't write the code of
// function 'virtual Parent* Parent::Intersection(Parent anotherParent)'
*tmp = this->vtParent.at(i)->Intersection(anotherParentVector.getParentVector().at(i));
result->getParentVector.push_back(tmp);
}
}
我没有写函数'virtual Parent* Parent::Intersection(Parent anotherParent)'的代码,所以我不能执行上面的代码。有人知道如何解决这个问题?
// 这里的想法是我想调用函数'Numeric* Intersection(Numeric anotherNumeric)' 或'Symbolic* Intersection(Symbolic anotherSymbolic)'
// FINISH,谢谢大家的建议。
【问题讨论】:
-
你有不同返回类型的虚函数。见this。
标签: c++ inheritance