是函数重载还是重载还是别的什么?( hello函数)
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();
}发布于 2012-03-22 22:54:39
两者都不是,它是隐藏的函数。
在派生类中声明具有相同名称(即使签名不同)的非虚函数将完全隐藏基类实现。
要仍然可以访问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) {}
};发布于 2012-03-22 23:10:51
覆盖:
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
};发布于 2012-03-22 22:55:17
这两者都不是。
覆盖是在子类中具有相同签名(相同的名称、参数和返回值)的函数。重载是一个名称相同但参数不同的函数。
https://stackoverflow.com/questions/9824724
复制相似问题