读书人

关于类继承的一些有关问题

发布时间: 2013-07-01 12:33:04 作者: rapoo

关于类继承的一些问题

class A {
public:
void f() {cout << "A: f()" << endl; h();}
private:
void h() {cout << "A: h()" << endl;}
};
class B : public A {
public:
void f() {this->A::f();}
private:
void h() {cout << "B: h()" << endl;}
};
int _tmain(int argc, _TCHAR* argv[])
{
B b;
b.f();
return 0;
}


运行结果如下
A: f()
A: h()

问题:父类的公有函数调用一个私有函数,怎样让子类继承这种调用关系,并且函数的运行结果和子类对象相关

[解决办法]
把基类中被调用的私有函数声明成virtual
派生类中不要声明那个公开的函数
google: template method pattern

读书人网 >C++

热点推荐