在C ++中重载派生类中的基类方法 [英] Overloading base class method in derived class in C++

查看:116
本文介绍了在C ++中重载派生类中的基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

using namespace std;

class B {
public:
	 void foo() { cout << "Inside B::foo()" << endl; }
};

class D :public B {
public:	
	void foo(int i) { cout << "Inside D::foo() and i is " << i << endl; }
};

int main()
{
	D d;
	d.foo();

	return 0;
}





以上程序无法编译错误'D :: foo':函数不带0参数



我试图理解派生类没有从基类获取foo()(不带参数)方法的原因是什么。 C ++在派生类中没有提供基类方法的真正限制或设计是什么。



我尝试过的方法:



阅读文章。不确定我们可以在C ++中引用所有可能问题的单一地方。



Above program fails to compile with an error 'D::foo': function does not take 0 arguments

I am trying to understand what is the reason that derived class did not get foo() (without arguments) method from base class. What is the real restriction or design for which C++ is not providing base class method in derived class.

What I have tried:

Reading articles. Not sure what is the single place which we can refer for all possible questions in C++.

推荐答案

D中foo的声明隐藏了B中的声明。

您需要使用添加作为单独的函数将其提升:

The declaration of foo in D hides the declaration in B.
You need to add using to "bring it forward" as a separate function:
#include <iostream>

using namespace std;

class B {
public:
	 void foo() { cout << "Inside B::foo()" << endl; }
};

class D :public B {
public:	
    using B::foo;
	void foo(int i) { cout << "Inside D::foo() and i is " << i << endl; }
};

int main()
{
	D d;
	d.foo();
	d.foo(666);
	return 0;
}


这篇关于在C ++中重载派生类中的基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆