C ++继承和函数覆盖 [英] C++ inheritance and function overriding

查看:150
本文介绍了C ++继承和函数覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,即使基本类的成员函数的原型(参数的计数,类型和常量)不同,它的同名的派生类函数是否会覆盖基类的成员函数?我想这是一个愚蠢的问题,因为许多网站说,函数原型应该是一样的发生;但为什么不下面的代码编译?这是一个非常简单的继承情况,我相信。

  #include< iostream> 
using std :: cout;
using std :: endl;

class A {};
class B {};

class X
{
public:
void spray(A&)
{
cout< A类<< endl;
}
};

class Y:public X
{
public:
void spray(B&)
{
cout< B类<< endl;
}
};

int main()
{
A a;
B b;
Y y;

y.spray(a);
y.spray(b);

return 0;
}

GCC throws

 错误:没有匹配的函数调用`Y :: spray(A&)'
注意:候选项是:void Y :: spray(B&)


解决方案

用于描述这个术语的术语是隐藏,而不是 。默认情况下,派生类的成员将使任何具有相同名称的基类的成员无法访问,无论它们是否具有相同的签名。如果要访问基类成员,可以使用使用声明将它们拉入派生类。在这种情况下,使用X添加以下到 class Y

  ::喷雾; 


In C++, will a member function of a base class be overridden by its derived class function of the same name, even if its prototype (parameters' count, type and constness) is different? I guess this a silly question, since many websites says that the function prototype should be the same for that to happen; but why doesn't the below code compile? It's a very simple case of inheritance, I believe.

#include <iostream>
using std::cout;
using std::endl;

class A {};
class B {};

class X
{
public:
    void spray(A&)
    {
        cout << "Class A" << endl;
    }
};

class Y : public X
{
public:
    void spray(B&)
    {
        cout << "Class B" << endl;
    }
};

int main()
{
    A a;
    B b;
    Y y;

    y.spray(a);
    y.spray(b);

    return 0;
}

GCC throws

error: no matching function for call to `Y::spray(A&)'
note: candidates are: void Y::spray(B&)

解决方案

The term used to describe this is "hiding", rather than "overriding". A member of a derived class will, by default, make any members of base classes with the same name inaccessible, whether or not they have the same signature. If you want to access the base class members, you can pull them into the derived class with a using declaration. In this case, add the following to class Y:

using X::spray;

这篇关于C ++继承和函数覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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