简体   繁体   English

调用从基础 class 继承的 class 的方法。 C++

[英]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.

相关问题 从基类类型的指针数组中调用派生类的方法。 (C ++) - Call a method of a derived class from an array of pointers of type base class. (C++) 从多重继承的模板化基础 class 覆盖 C++ 方法 - Override C++ method from multiply inherited templated base class 是否可以从C ++的派生类中调用基类中的方法? - is it possible to call a method in the base class from a derived class in c++? C ++如何从基类调用派生类中的方法 - C++ how to call method in derived class from base class C ++继承的方法调用基类的方法,而不是重载的方法 - C++ inherited methods call the base class's method instead of overloaded method 从基类继承的C ++公共方法无法访问派生类中的私有成员变量 - C++ public method inherited from base class can not access private member variable in derived class C++ - 如何调用递归继承的模板化基础 class 的模板化方法 - C++ - How to call a templated method of a recursively inherited templated base class C ++继承的虚方法仍然使用基类实现 - C++ Inherited Virtual Method Still Uses Base Class Implementation C ++将继承的类自动转换为基类 - c++ autoconvert inherited class to base class 自动调用C ++基类方法 - Call a C++ base class method automatically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM