【发布时间】:2023-12-25 05:45:01
【问题描述】:
我正在开发一个使用类继承并且在基类和派生类中都需要大量重载的项目,我已经简化了代码,但我不想不必要地复制和粘贴,因为这应该是继承是为了。
#include <iostream>
class Base
{
public:
Base() = default;
//base const char* overload
void foo(const char* message)
{
std::cout << message << std::endl;
}
//other overloads ...
};
class Derived : public Base
{
public:
Derived() = default;
//derived int overload
void foo(int number)
{
std::cout << number << std::endl;
}
};
int main()
{
Derived b;
b.foo(10); //derived overload works
b.foo("hi"); //causes error, acts as if not being inherited from Base class
return 0;
}
【问题讨论】:
-
在
Derived的正文中添加using Base::foo;。否则,只有Derived::foo重载可见。问题不是重载解析,而是名称查找。 -
常见问题 - 不是 Q 或 A 的最清晰的提炼,而是例如:*.com/a/16837660/410767 / 这个问题的“为什么”版本:*.com/q/1628768/410767
标签: c++ polymorphism overloading using-declaration name-hiding