C++中的关键概念:名字查找与继承(一道面试题)
大侠们给讲解下,不是很明白!//tt.h
#include<iostream>
using std::cout;
using std::endl;
class A {
protected:
int m_data;
public:
A(int data=0)
{
m_data = data;
}
int GetData()
{
return doGetData();
}
virtual int doGetData()
{
return m_data;
}
};
class B: public A
{
protected:
int m_data;
public:
B(int data = 1)
{
m_data = data;
}
int doGetData()
{
return m_data;
}
};
class C: public B
{
protected:
int m_data;
public:
C(int data=2)
{
m_data = data;
}
};
class Base
{
public:
virtual int fun()
{
cout << "base: virtual int fun()" << endl;
return 0;
}
};
class D1 : public Base
{
public:
int fun(int)
{
cout << "D1: int fun(int)" << endl;
return 0;
}
int myfun(int, int)
{
cout << "Two int" << endl;
return 0;
}
};
class D2 : public D1
{
public:
int fun(int)
{
cout << "D2: int fun(int)" << endl;
return 0;
}
int fun()
{
cout << "D2: int fun()" << endl;
return 0;
}
int myfun(int, int, int)
{
cout << "Three int" << endl;
return 0;
}
};
//tttest.cpp
#include"tt.h"
int main()
{
C c(10);
cout << c.GetData() << endl;
cout << c.A::GetData() << endl;
cout << c.B::GetData() << endl;
cout << c.C::GetData() << endl;
cout << c.doGetData() << endl;
cout << c.A::doGetData() << endl;
cout << c.B::doGetData() << endl;
cout << c.C::doGetData() << endl;
D2 d2;
//d2.myfun(2,2); //“D2::myfun”: 函数不接受 2 个参数。同一个类中定义的函数才可以重载,继承来的不行。
d2.myfun(2,2,2);
system("pause");
return 0;
}
大侠们给讲解下,不是很明白!