重载和覆盖--关于virtual


在派生类中重新定义基类的成员函数时将隐藏基类中所有同名的函数。

//: C15:NameHiding2.cpp

// Virtual functions restrict overloading

#include <iostream>

#include <string>

using namespace std;

class Base {

public:

virtual int f() const {

cout << "Base::f()/n";

return 1;

}

virtual void f(string) const {}

virtual void g() const {}

};

 

class Derived1 : public Base {

public:

void g() const {}

};

 

 

 

int main() {

string s("hello");

Derived1 d1;

int x = d1.f();

d1.f(s);

Derived2 d2;

x = d2.f();

//!d2.f(s); // string version hidden

Derived4 d4;

x = d4.f(1);

//!x = d4.f(); // f() version hidden

//!d4.f(s); // string version hidden

Base& br = d4; // Upcast

//!br.f(1); // Derived version unavailable

br.f(); // Base version available

br.f(s); // Base version abailable

} ///:~

class Derived2 : public Base {

public:

// Overriding a virtual function:

int f() const {

cout << "Derived2::f()/n";

return 2;

}

};

 

class Derived3 : public Base {

public:

// Cannot change return type for virtual:

//! void f() const{ cout << "Derived3::f()/n";}

};

class Derived4 : public Base {

public:

// Change argument list:

int f(int) const {

cout << "Derived4::f()/n";

return 4;

}

};

 

 

Base::f()

 

 

Derived2::f()

覆盖基类的某重载函数时将隐藏其他所有重载版本,无论被覆盖的是否为虚函数。

 

Derived4::f()

改变了参数形式,不是覆盖,将隐藏基类中所有同名函数。

 

无法通过基类指针操作其不含有的成员函数

Base::f()

此时为基类指针,f()f(string)并没有被覆盖。

 

Derived3中,覆盖虚函数时不能改变返回值类型,但是非虚函数可以改变返回值类型。因为在通过基类指针多态调用虚函数时,其期待的返回值为int类型,若此时基类指针指向的是Derived3类型时,则将调用Derived3void f() const,没有返回值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值