C++重写,重载,重定义

2016-08-02  本文已影响66人  司马捷
ObjectDiagram1.png
//
//  main.cpp
//  C++重载重写重定义
//
//  Created by 扆佳梁 on 16/8/2.
//  Copyright © 2016年 Eric. All rights reserved.
//

#include <iostream>
using namespace std;

class Parent{
public:
    void abc(){
        cout<<"abc"<<endl;
    }
    
    virtual void func(){
        cout<<"func() do"<<endl;
    }
    virtual void func(int i){
        cout<<"func() do ..."<<i<<endl;
        
    }
    
    void func(int i,int j){
        
        cout<<"func() do ..."<<i<<" "<<j<<endl;
    }
    
    virtual void func(int i,int j,int m,int n){
        cout<<"func() do "<<i<<" "<<j<<m<<n<<endl;
    }
    
};

class Child:public Parent{
public:
    void abc(){
        cout<<"child abc"<<endl;
    }
    
    void func(int i,int j){
        cout<<"child func do "<<endl;
    }
    
    virtual void func(int i,int j,int k){
        cout<<"child func(int i,int j,int k)"<<endl;
    }
    
};

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    
    Child c1;
    //c1.func()会报错
//1 C++编译器 看到func名字 ,因子类中func名字已经存在了(名称覆盖).所以c++编译器不会去找父类的4个参数的func函数
//2 c++编译器只会在子类中,查找func函数,找到了两个func,一个是2个参数的,一个是3个参数的.
//3 C++编译器开始报错.....  error C2661: “Child::func”: 没有重载函数接受 4 个参数
//4 若想调用父类的func,只能加上父类的域名..这样去调用..

    c1.Parent::func();
    c1.func(1, 2);
    Parent *p = NULL;
    p = &c1;
    p->abc();
    
     return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读