[英]Call a method of the inherited class from the base class. C++
I want a function that receives a vector with elements of the base class and executes the method of the corresponding inherited class.我想要一个 function,它接收一个带有基本 class 元素的向量并执行相应继承的 class 的方法。 I don't know if I should define a virtual function in the base class.我不知道是否应该在基础 class 中定义一个虚拟 function。 Anyway it can't be a pure virtual function as long as I don't want the inherited classes to be abstract.无论如何,只要我不希望继承的类是抽象的,它就不能是纯虚拟 function。
class A {
public:
void printSubclass() {
std::cout << "No subclass found";
}
};
class B : public A {
public:
void printSubclass() {
std::cout << "Subclass B";
}
};
class C : public A {
public:
void printSubclass() {
std::cout << "Subclass C";
}
};
void function(vector<A> MyVec) {
for(int k=0; k<Myvec.size(); k++)
MyVec[k].printSubclass();
}
int main() {
B ObjB;
C ObjC;
vector<A> MyVector= {ObjB, ObjC}
function(ObjB);
return 0;
}
You will need to make printSubclassvirtual (whether pure or not would depend on whether actual objects of 'A' make sense rather than on anything to do with the derived classes).您将需要使 printSubclassvirtual (是否纯粹取决于“A”的实际对象是否有意义,而不是与派生类有关)。 And tregardless of whether printSubclass is pure the vector will need to be of A* rather than A objects directly.并且不管 printSubclass 是否是纯的,向量都需要是 A* 而不是 A 直接的对象。 With the vector holding 'A' objects whenever you put non-A objects into the vector the non-A portions get sliced off.每当您将非 A 对象放入向量中时,向量都持有“A”对象,非 A 部分会被切掉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.