【问题标题】:Overloading virtual method in derived class with different signature在具有不同签名的派生类中重载虚拟方法
【发布时间】:2021-02-07 05:45:15
【问题描述】:

拥有

  • 定义虚方法的 BASE 类
  • 一个 DERIVED 类,它定义了一个同名但签名不同的虚拟方法

当使用指向 DERIVED 类的指针从另一个类调用时,编译器抱怨它无法在 BASE 类中找到正确的函数。

示例(省略构造函数等):

class BASE {
    public: virtual int print(std::vector<double>& values);
};

int BASE::print(std::vector<double>& values){
    std::cout << "This is the base class!" << std::endl;
}
class DERIVED : public BASE {
    public: void virtual print(int a, int b);
};

void DERIVED::print(int a, int b){
    std::cout << "This is the derived class from int-method!" << std::endl;
}
class TEST {
    public: void testit();
};

void TEST::testit(){
    DERIVED derived;
    std::vector<double> a;
    derived.print(a);
}

编译器抱怨TEST.cpp:30:17: error: no matching function for call to ‘DERIVED::print(std::vector&lt;double&gt;&amp;)

如何在派生类中重载具有不同签名的虚函数?例如,这对于添加 BASE 类中不可用的功能可能很有用。

【问题讨论】:

  • 要覆盖函数,它们需要具有完全相同的签名。
  • 我想你的意思是覆盖,而不是超载。您不能覆盖具有不同签名的方法。
  • 如果您实际上是指超载,请在问题中包含minimal reproducible example 和完整的错误消息
  • 这能回答你的问题吗? stackoverflow.com/questions/11912022/…
  • 这些函数都不是公开的,因此print 变体都不能供Test::testit 调用。

标签: c++ overriding virtual


【解决方案1】:

DERIVED 中的print 阴影print 中的BASE,即使签名不同。

要修复,请将using BASE::print; 添加到DERIVED。注意这一行可以改变继承函数的访问修饰符;如果您希望函数为public,则using ... 也必须为public

请注意,您不会在此处覆盖任何函数(usually 只有在签名相同的情况下才有可能)。您创建了两个具有相同名称的不相关函数。这意味着可以删除virtual,除非您计划添加更多派生类并实际覆盖其中的函数。

【讨论】:

  • 谢谢 - 明白了!将public: using BASE::print; 添加到 DERIVED 类就可以了!那么在派生类中重载这些方法时隐藏/隐藏 BASE 类的所有方法背后的逻辑是什么?我认为不这样做不会有歧义吗?!?
  • @sputn1k 这样做可能是为了确保您可以安全地向基类添加新方法,而不必担心派生类在具有相同名称的方法时会默默地改变行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多