您的位置:首页 > 其它

如何使用多态性数组

2007-10-24 22:42 288 查看
1)错误的使用多态性数组

详细请见《More Effective C++》条款3,此处只贴出示例代码:

#include <iostream>
#include <string>
using namespace std;

class B
{
public:
virtual void print() const
{
cout << "B" << endl;
};
};

class D : public B
{
public:
virtual void print() const
{
cout << "D" << endl;
};
private:
int i;
};

void printArray(const B b[], int size)
{
for (int i = 0; i < size; ++i)
{
b[i].print();
}
}

int main()
{
B b[10];
printArray(b, 10);

D d[10];
printArray(d, 10); //因为B和D的大小不同,所以此处程序会崩溃
return 0;
}

2)为了使C++应用观察者模式,应该这样使用多态数组:

#include <iostream>
#include <string>
#include <list>
using namespace std;

class B
{
public:
virtual void print() const
{
cout << "B" << endl;
};
};

class D : public B
{
public:
virtual void print() const
{
cout << "D" << endl;
};
private:
int i;
};

void printArray(const list<B*>& bLst)
{
for (list<B*>::const_iterator it = bLst.begin(); it != bLst.end(); ++it)
{
(*it)->print();
}
}

int main()
{
list<B*> bLst;
B* pb = NULL;
pb = new B;
bLst.push_back(pb);

pb = new B;
bLst.push_back(pb);

pb = new D;
bLst.push_back(pb);

pb = new D;
bLst.push_back(pb);

printArray(bLst);

for (list<B*>::const_iterator it = bLst.begin(); it != bLst.end(); ++it)
{
delete (*it);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: