您的位置:首页 > 其它

NVI

2016-04-16 12:03 423 查看
这是我写的简易版的, Effective C++, 3rd Edition, Item 35: 考虑可选的 virtual functions(虚拟函数)的替代方法

#include<iostream>//item 35
using namespace std;
/*------------------NVI--------------------*/
class A{
public:
void f()
{
f1();
cout << "f";
}
private:
//protected:
virtual void f1()
{
cout << "A::f1";
}
};

class B : public A
{
//public:
virtual void f1()
{
cout << "B::f1";
}
};


书上的程序

/*virtual*/
class GameChareter1
{
public:
virtual int healthVaule()const;
};

/*strategy*/
class GameChareter
{
public:
typedef int (*GameHealthCalcFcn) (GameChareter);// '*' zai qianmian
GameChareter(GameHealthCalcFcn ht = defaultHealht):
health(ht) { }

int healthvaule()const
{
return health(*this);//this is a fucking fcn
}
private:
GameHealthCalcFcn health;
};


//类里面什么都没有(关于血量),这样只有通过一个指针调用类外函数,来返回当前血量,

//而且你也必须在类外定义掉血方式,这样一来,用过指针调用的函数,又有定义多个的必要了

//

//定义类外函数,然后把指针返回给类内指针,才是正道,把定义的函数指针,来创建函数是错误的想法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: