使用继承的通用函数 [英] Using Inheritance for Generic Functions

查看:128
本文介绍了使用继承的通用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个模板类,多个孩子覆盖模板的方法(我相信我做的正确)。

I am trying to create a template class with multiple children that override the template's methods (I believe I did this correctly). I then want a single function that can work with all of the children.

例如:

#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 的打印方法 inherit_b 已输入到 print_function

This prints "base" like I would expect, however I would like it to use inherit_a's print method or inherit_b's print method if inherit_b was imputed to print_function. Is something like this possible?

推荐答案

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

What you’re looking for is called subtype polymorphism; in C++, only reference types allow polymorphic virtual function calls to work as you expect. You can use a reference:

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

或指针:

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

您已完成的操作按 ,复制对象的 base 部分 - 这被称为切片

What you have done passes the object by value, copying the base portion of the object only—this is called slicing:

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

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

Note that since your print() member function does not modify the object, it can and ought to be declared const. Also, (void) in parameter lists is C style and redundant in C++; use () instead.

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

const 部分签名,所以子类也必须指定它:

The const is part of the signature, so subclasses must also specify it:

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

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

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

或指向 const object:

Or a pointer to a const object:

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

这说明 print_function()也不修改其参数。

This documents that print_function() also does not modify its argument.

这篇关于使用继承的通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆