跨基类和继承类的方法参数的多态性
我有以下内容:
#include <iostream>
using std::cout;
class General {
public:
General() {};
void print(void) {
cout << "From General\n";
}
};
class Special : public General {
public:
Special() {};
void print(int c) {
cout << "From Special\n";
}
};
int main() {
Special s;
s.print(3); // want to print from Special
s.print(); // want to print from General
}
我希望看到的输出是:
From Special
From General
但是,我收到此编译错误(指的是最后一个 print()
调用):
error #165: too few arguments in function call
我希望编译器能够识别哪个 print
方法根据我提供的参数的数量和类型来调用。如果这两个方法定义在同一个类中,那么它会完美地工作。但在这里,它们分为基类和派生类。
有办法做到这一点吗?
I have the following:
#include <iostream>
using std::cout;
class General {
public:
General() {};
void print(void) {
cout << "From General\n";
}
};
class Special : public General {
public:
Special() {};
void print(int c) {
cout << "From Special\n";
}
};
int main() {
Special s;
s.print(3); // want to print from Special
s.print(); // want to print from General
}
The output that I would like to see is:
From Special
From General
However, I get this compilation error (referring to the very last print()
call):
error #165: too few arguments in function call
I want the compiler to recognize which print
method to call based on the number and types of arguments I provide. If these 2 methods were defined within the same class, then it would work perfectly. But here, they are split across the base and derived classes.
Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过在
Special
内添加 using 声明 来实现此目的,如下所示。这是有效的,因为基类成员函数的 using 声明(如您的例子中的 print )将该函数的所有重载实例添加到派生类的范围中。演示
You can achieve this by adding a using declaration inside
Special
as shown below. This works because a using declaration for a base-class member function(likeprint
in your case) adds all the overloaded instances of that function to the scope of the derived class.Demo
这个怎么样:
How about this: