C++ 模板:重载时找不到基类类型参数方法
C++ Template: cannot find base class type parameter method when overloaded
请考虑以下示例:
#include <iostream>
class Base {
public:
virtual void foo(std::string str) = 0;
void foo() { foo("LOL"); }
};
class Derived : public Base {
public:
void foo(std::string str) { std::cout << str << std::endl; }
};
template<class T> class MyTemplate {
public:
void print() { a.foo(); }
T a;
};
int
main(int argc, char** argv)
{
MyTemplate<Derived> a;
a.print();
}
编译时,出现以下错误:
main.cpp: In instantiation of ‘void MyTemplate<T>::print() [with T = Derived]’:
main.cpp:24:11: required from here
main.cpp:16:18: error: no matching function for call to ‘Derived::foo()’
void print() { a.foo(); }
^
main.cpp:16:18: note: candidate is:
main.cpp:11:8: note: virtual void Derived::foo(std::string)
void foo(std::string str) { std::cout << str << std::endl; }
^
main.cpp:11:8: note: candidate expects 1 argument, 0 provided
它发现解决方案是编写:
void print() { a.Base::foo(); }
但这是为什么呢?为什么 G++ 自己找不到 Base::foo(( 方法?
谢谢
原因是类Derived
中foo
的方法隐藏了从类Base
继承的所有同名方法。因此,只有接受std::string
作为参数的方法foo
的单个版本可用于通过Derived
调用。因此,您必须使用以下语法调用不接受任何参数的foo
:
a.Base::foo();
请注意,您还可以使用 using 声明使继承foo
Derived
类中可见:
class Derived : public Base {
public:
using Base::foo;
void foo(std::string str) { std::cout << str << std::endl; }
};
通过此更改,下一个代码将生效:
a.foo();
相关文章:
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 为什么允许dynamic_cast到非唯一的基类类型?
- 基类类型向量中的派生结构
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何隐藏模板基类的参数类型
- C++ 模板:重载时找不到基类类型参数方法
- 是否可以从构造函数自动推断基类模板参数?
- 如果类包含基类类型的成员作为第一个元素,后跟其他成员,编译器是否可以优化空基?
- 如何在不转换回基类类型的情况下返回派生类型的对象?
- 通过派生类模板参数指定基类模板参数之一。如何使用基类的 using 声明
- 如何编写指定模板化基的类型参数的派生类
- 声明基类类型的指针,但随后通过指向子类来实例化它.这是良好的编程实践吗?
- 获取继承基类类型的元组
- 如何从指针调用派生类函数到基类类型 (C++)
- 有没有办法从基类函数参数中推断出模板参数
- 如何将unique_ptr用作参数到需要基类作为参数的函数
- 如何检查对象是否是基类类型
- 采用基类类型参数的虚拟函数
- 子类对象,用作定义为c++基类类型的参数