重载、覆盖、隐藏

重载、覆盖、隐藏
1 C++重载的发生条件
参数列表不同:(参数个数、顺序、类型)
2 extern“C”处理
3 隐式类型转换导致重载函数产生二义性

void output(int x)
{
	cout << " output int " << x << endl;
}

void output(float x)
{
	cout << " output float " << x << endl;
}


output(0.5)

因为程序的隐式转换,编译器不知道要调用哪个函数

4、重载覆盖、隐藏
重载的条件:同一个类中,参数列表不同
覆盖的条件:父子类中,参数列表完全相同,有Virtual关键字,多态性(父类指针指向子类)
隐藏条件两种情况:
<1> 函数名相同的情况下,子类基类的参数列表不同,此时无论父类的函数有没有virtual关键字,都会有隐藏
<2> 函数名相同的情况下,父类函数没有virtual关键字

5、子类调用父类

class Base
{
public:
    void f(int x);
};

class Derived : public Base
{
    public:
void f(char *str);
};

void Test(void)
{
    Derived *pd = new Derived;

    pd->f(10);    // error
}
// 正确写法
class Derived : public Base
{
public:
    void f(char *str);
    void f(int x) 
    { 
        Base::f(x); 
    }
};

6、参数缺省值
<1>、注意只能在函数的声明中缺省
void Foo(int x=0, int y=0); // 正确,缺省值出现在函数的声明中>
<2>、如果函数有多个参数,参数只能从后向前挨个儿缺省


正确的示例如下:
void Foo(int x, int y=0, int z=0);
错误的示例如下:
void Foo(int x=0, int y, int z=0);

<3> 当心二义性

#include <iostream.h>
void output( int x);
void output( int x, float y=0.0);
void output( int x)
{
    cout << " output int " << x << endl ;
}
 
void output( int x, float y)
{
    cout << " output int " << x << " and float " << y << endl ;
}
 
void main(void)
{
    int x=1;
    float y=0.5;
//  output(x);          // error! ambiguous call
    output(x,y);        // output int 1 and float 0.5
}

7、运算符重载
运算符与普通函数在调用时的不同之处是:对于普通函数,参数出现在圆括号内;
而对于运算符,参数出现在其左、右侧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值