是超载还是覆盖功能?

时间:2012-03-22 14:53:04

标签: c++ overloading override

是函数重载还是覆盖还是其他什么? (你好功能)

class A {

public:
    void hello(int x) { cout << "A" << endl; }

};

class B : public A {

public:
    void hello() { cout << "B" << endl; }

};

void main() {

    B obj;
    obj.hello();

}

4 个答案:

答案 0 :(得分:9)

它不是,它的功能隐藏

在派生类中声明具有相同名称的非虚函数(即使签名不同)会完全隐藏基类实现。

要仍然可以访问A::hello,您可以执行以下操作:

class B : public A {
public:
    using A::hello;
    void hello() { cout << "B" << endl; }
};

重写:

struct A
{
   virtual void foo() {}
};
struct B : public A
{
   /*virtual*/ void foo() {}
};

重载:

struct A
{
   void foo() {}
   void foo(int) {}
};

答案 1 :(得分:2)

重写:

struct Base {
    virtual void Foo() { std::cout << "Base\n"; };
};

struct Derived : Base {
    virtual void Foo() { std::cout << "Derived\n"; };
    // same name and signature as a virtual function in a base class,
    // therefore this overrides that function. 'virtual' is optional in
    // the derived class (but you should use it).
};

C ++ 11增加了一种确保函数覆盖的方法:

struct Derived : Base {
    virtual void Foo() override { std::cout << "Derived\n"; };
};

现在,如果方法Foo没有覆盖某些内容,那么您将收到错误。

struct Base {
   void Foo();
};

struct Derived : Base {
   virtual void Foo() override; // error, Derived::Foo is hiding Base::Foo, not overriding 
};

答案 2 :(得分:0)

这不是。

Overriding是一个在子类中具有相同签名(相同名称,参数和返回值)的函数。重载是一个具有相同名称但参数不同的函数。

答案 3 :(得分:0)

它不是重载函数,因为在函数重载中,参数数量或参数类型应该不同。例如:

void show(int a,int b);
void show(int a);
void show(char a,char b);

并且它都不是函数重写,因为在重写函数原型中必须是相同的。例如: 具有函数的基类和派生类 void show(); //function prototype must be same

相关问题