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()