c++ - 对泛型函数使用继承

标签 c++ inheritance

我正在尝试创建一个包含多个重写模板方法的子类的模板类(我相信我这样做是正确的)。然后我想要一个可以与所有子项一起使用的函数。

例如:

#include <iostream>
using namespace std;

class base{
public:
    virtual void print(void){
        cout << "Base" << endl;
    }
};

class inherit_a : public base{
public:
    virtual void print(void) override{
        cout << "inherit_a" << endl;
    }
};

class inherit_b : public base{
public:
    virtual void print(void){
        cout << "inherit_b" << endl;
    }
};

void print_function(base item){
    item.print();
}


int main(){
    inherit_a item_a;
    print_function(item_a);
    return(0);
}

这会像我期望的那样打印“base”,但是我希望它使用 inherit_a 的打印方法或 inherit_b 的打印方法 if inherit_b 归因于 print_function。这样的事情可能吗?

最佳答案

你要找的是子类型多态性;在 C++ 中,只有引用类型允许多态 virtual 函数调用按预期工作。您可以使用引用:

void print_function(base& item){
    item.print();
}

或者一个指针:

void print_function(base* item){
    item->print();
}

您所做的按值传递对象,仅复制对象的base部分——这称为切片:

void print_function(base item){
    item.print();
}

请注意,由于您的 print() 成员函数不修改该对象,因此可以并且应该将其声明为 const。此外,参数列表中的 (void) 是 C 风格的,在 C++ 中是多余的;使用 () 代替。

virtual void print() const {
    cout << "Base" << endl;
}

const 是签名的一部分,因此子类也必须指定它:

virtual void print() const override {
    cout << "inherit_a" << endl;
}

然后 print_function() 可以获取对 const 对象的引用:

void print_function(const base& item){
    item.print();
}

或者指向const 对象的指针:

void print_function(const base* item){
    item->print();
}

这说明 print_function() 也没有修改它的参数。

关于c++ - 对泛型函数使用继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15306367/

相关文章:

c++ - 找到 cin 和 ifstream 的流结尾?

c++ - 以不同用户身份运行的两个 exe 如何使用 COM(组件对象模型)进行通信

c++ - 使用非默认构造函数初始化自定义类的继承类

python - super().method() 与 super(self.__class__,self).method() 的区别

c++ - batchedgemm源代码?

c# - 如何在我的 C# 代码中调用库中的 C 方法?

c++ - C++ 中零初始化值的 float 比较

c# - 我如何继承字典?

java - 抽象类为 parcelable

python - 控制Python数据类继承类时的初始化顺序