C++重载重写重定义

27 篇文章 0 订阅

在C++中有三个很相似的概念,很容易混淆。
下面就来总结区分,下面是测试代码
不过在分析代码之前先来分析一下关于上面的三个名词的概念
重载:1)必须在同一个类中,2)函数名相同,参数列表不同;
重写:1)必须发生在父子类中,2)函数名声明完全一致,且在父类中必须是虚函数;
重定义:1)必须发生在父子类中,2)函数名相同,且在父类中不是虚函数;

以上三个定义应该很好理解[个人总结,如有错误,请自行区分]

#include <iostream>
using namespace std;

class A
{
    public:
    void print(){cout << "this A\n";}
    virtual void print(int a){cout << "test A" << a;}
};
class B:public A
{
    public:
    void print(int a,int b){cout << "this B" << a << b;}
    virtual void print(int b){cout << "test B" << b;}
};

关于如何编写测试用例,请根据上面的概念自行编写,这里我主要相对重定义进行一下测试。
c
int main(void)
{
A aa;
B bb;
bb.print();
}

编译结果:

test.cpp: In function ‘int main()’:
test.cpp:21:11: error: no matching function for call to ‘B::print()’
  bb.print();
           ^
test.cpp:21:11: note: candidates are:
test.cpp:13:7: note: void B::print(int, int)
  void print(int a,int b){cout << "this B" << a << b;}
       ^
test.cpp:13:7: note:   candidate expects 2 arguments, 0 provided
test.cpp:14:15: note: virtual void B::print(int)
  virtual void print(int b){cout << "test B" << b;}
               ^
test.cpp:14:15: note:   candidate expects 1 argument, 0 provided
可以看出子类不可以调用从父类那里继承过来的同名函数,这是因为子类覆盖了父类的函数名。如果此时一定要调用父类的同名方法必须要加上域名运算符::.
bb.A::print();即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值