【问题标题】:How to make working variadic arguments method inheritance with same method overloaded on child class [duplicate]如何使用子类上重载的相同方法使工作可变参数方法继承[重复]
【发布时间】:2019-07-22 00:29:48
【问题描述】:

以下代码有效:

class Test_Interface {
public:
    template<typename... Args>
    void Split(int weight, Args... args){
        Split(weight);
        Split(args...);
    }

    virtual void Split(int weight) {
        std::cout << "Test_Interface::Split weight: " << weight << std::endl;
    };
};

class Test : public Test_Interface {};

int main()
{
    Test test;
    test.Split(1, 20, 300);
}

但如果我在 Test 类中为方法 Split 定义重载,例如:

class Test : public Test_Interface {
public:
    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};

然后我得到如下错误:error: no matching function for call to 'Test::Split(int, int, int)'

我知道如果我也在类 Test 中定义可变参数方法,例如:

class Test : public Test_Interface {
public:
    template<typename... Args>
    void Split(int weight, Args... args){
        Split(weight);
        Split(args...);
    }

    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};

它再次工作,但它并没有做最初打算做的事情,它只有一个地方(接口)定义可变参数方法,并且每个派生类仅具有非可变参数方法的自定义实现.我的目标是避免一遍又一遍地复制粘贴相同的代码并在多个地方维护它。为什么子类不重载方法继承工作?有没有办法不用复制粘贴?谢谢

【问题讨论】:

标签: c++ inheritance variadic-functions


【解决方案1】:

当您声明Test::Split 函数时,您隐藏继承的函数。之后,当您在 Test 对象上使用 Split 时,编译器只知道 Test::Split 而不是父函数 Test_Interface::Split

解决方案很简单:将父类中的符号拉入Test 类:

class Test : public Test_Interface {
public:
    using Test_Interface::Split;  // Pull in the Split symbol from the parent class

    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多