如何使用多态性数组
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;
}
详细请见《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;
}
相关文章推荐
- 在PB中如何使用一个字符串给一个字符串数组赋值
- MSIL 教程(二):数组、分支、循环、使用不安全代码和如何调用Win32 API
- Android开发中如何定义和使用数组
- 不要使用多态性数组
- iOS如何在数组中使用弱引用(weak reference)
- 如何使用fiddler2拦截移动端app的数组请求
- js:数组重排序问题:如何使用sort()方法按数值的大小进行升序或降序排列
- 在C++中如何将ActiveX控件所使用的BSTR数据转换成CHAR字符数组?
- 如何使用数组
- 如何不使用for循环实现数组倒序
- SQL Server存储过程中如何使用数组参数
- 二维数组做函数参数,如何将三维数组降为二维数组,指向数组的指针的使用
- 如何动态的定义及使用数组呢?
- Java基础---如何使用Java中的数组(三十)
- 使用lua CJSON库如何将空table编码成数组
- springMVC如何使用@RequestParam传递数组类型参数
- c语言动态调整数组大小如何使用realloc
- 本篇主要演示如何使用Jackson对List, Map和数组与JSON互相转换.
- VB中如何声明及使用多维数组,多层数组及动态数组
- MSIL 教程(二):数组、分支、循环、使用不安全代码和如何调用Win32 API(转)