注册 登录
编程论坛 C++教室

请问C++类的私有派生,如何使用派生类的对象调用基类的函数?

w2009w 发布于 2015-06-21 17:07, 550 次点击
定义一个基类Base,有两个公有成员函数fu1(),fu2(),私有派生出Derived类,如何通过Derived类的对象调用基类的函数fu1()。
#include<iostream>
using namespace std;
class Base
{
public:
    int fu1()
    {
        cout<<"Base func 1"<<endl;
        return 0;
    }
    int fu2()
    {
        cout<<"Base func 2"<<endl;
        return 0;
    }
};
class Derived:private Base{};
int main()
{
    Derived a;
    a.Base::fu1();
    return 0;
}
派生类的函数体和调用代码不知道怎么写啊?
6 回复
#2
yangfrancis2015-06-21 21:29
class Derived:private Base
{
public:
    zi1(){cout<<"Derived func1\n";}//函数体根本就是随便你怎么写,或者你可以不写
};
int main()
{
    Derived a;
    a.fu1();//调用父类函数
    return 0;
}


#3
w2009w2015-06-22 10:04
有错误,这样不对的!
1>d:\c++语言程序设计\7-9\7-9\7-9.cpp(25) : error C2247: 'Base::fu1' not accessible because 'Derived' uses 'private' to inherit from 'Base'
#4
w2009w2015-06-22 10:21
正确解答:
#include<iostream>
using namespace std;
class Base
{
public:
    int fu1()
    {
        cout<<"Base func 1"<<endl;
        return 0;
    }
    int fu2()
    {
        cout<<"Base func 2"<<endl;
        return 0;
    }
};
class Derived:private Base
{
public:
    int fu1(){return Base::fu1();}
    int fu2(){return Base::fu2();}
};
int main()
{
    Derived a;
    a.fu1();//调用父类函数
    return 0;
}
#5
yangfrancis2015-06-22 10:59
换成公有继承看看
#6
w2009w2015-06-22 11:28
公有继承当然可以了,我要的就是私有继承的情况!
#7
绝尘鑫醉2016-12-13 09:21
这样OK么?
#include<iostream>
using namespace std;
class Base{
    public:
        Base(){}
        ~Base(){}
        void fn1(){
            cout<<"fn1"<<endl;
        }
        void fn2(){
            cout<<"fn2"<<endl;
        }
};
class Derived:private Base{
    public:
        Derived(){}
        ~Derived(){}
        void lalala(){
            Base::fn1() ;
        }
};
int main(){
    Derived a;
    a.lalala() ;
    return 0;
}
1