C++(6)——子类调用父类函数实现

本文介绍C++中子类如何调用父类的函数,并通过具体实例演示了不同作用域下函数调用的过程及结果。文章展示了通过域操作符(::)指定调用哪个基类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++(6)——子类调用父类函数实现

在C++中子类对象调用父类函数可通过域操作符(::)来实现,表明所调用函数的作用域。

#include<iostream>

using namespace std;

class one {
public:
    // one() = default;
    one(int x=1) : m_one(x){
        cout << "one()" << endl;
    }
    virtual ~one(){
        cout << "~one()" << endl;
    }
    int GetData() {
        return dodata();
    }
    virtual int dodata() {
        return m_one;
    } 
private:
    int m_one;
};

class two : public one {
public:
    two(int x=2) : m_two(x){
        cout << "two()" << endl;
    }

    ~two(){
        cout << "~two()" << endl;
    }

    int dodata() {
        return m_two;
    } 
private:
    int m_two;
};

class three : public two {
public:
    three(int x) : m_three(x){
        cout << "three()" << endl;
    }

    ~three(){
        cout << "~three()" << endl;
    }
    
    int dodata() {
        return m_three;
    } 
private:
    int m_three;
};



int main() {
    three t(3);
    cout << t.GetData() << endl;
    cout << t.one::GetData() << endl;
    cout << t.two::GetData() << endl;
    cout << t.three::GetData() << endl << endl;

    cout << t.dodata() << endl;
    cout << t.one::dodata() << endl;
    cout << t.two::dodata() << endl;
    cout << t.three::dodata() << endl;
}
one()
two()
three()
3
3
3
3

3
1
2
3
~three()
~two()
~one()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值