@
ini 万分感谢哦,经过您的指点,我改成下面这样子完美通过编译和运行,大神看下还有哪里需要改动或者优化不 嘿嘿
```c++
#include <cstdlib>
#include <iostream>
class Package{
private:
int num;
public:
Package() = delete;
Package(int num){
std::cout << "create Package " << num << std::endl;
this->num = num;
}
Package(Package& o){
std::cout << "copy Package " << o.num << std::endl;
num = o.num;
}
virtual ~Package(){
std::cout << "delete Package " << num << std::endl;
}
virtual operator int(){
return num;
}
};
class Package2 : public Package{
private:
int num2;
public:
Package2() = delete;
Package2(int num):Package(-1){
std::cout << "create Package2 " << num << std::endl;
this->num2 = num;
}
Package2(Package2& o):Package(-1){
std::cout << "copy Package2 " << o.num2 << std::endl;
num2 = o.num2;
}
virtual ~Package2(){
std::cout << "delete Package2 " << num2 << std::endl;
}
virtual operator int(){
return num2;
}
};
template<class T>
class Container{
private:
struct contentContainer{
T content;
bool isUse;
};
contentContainer *contents;
int size;
public:
Container(int size){
contents = (contentContainer *)::malloc(sizeof(contentContainer) * size);
for(int i = 0; i < size; ++i)
contents[i].isUse = false;
this->size = size;
}
~Container(){
for(int i = 0; i < size; ++i){
auto &con = contents[i];
if (con.isUse){
con.content.~T();
}
}
free(contents);
}
void set(int pos, T content){
auto &con = contents[pos];
if (con.isUse){
con.content = content;
}else{
new(&con.content) T(content);
con.isUse = true;
}
}
T& get(int pos){
return contents[pos].content;
}
};
int main(int argc, char **argv) {
// 测试 Package 和 Package2 的大小
std::cout << "sizeof(Package): " << sizeof(Package) << std::endl;
std::cout << "sizeof(Package2): " << sizeof(Package2) << std::endl << std::endl;
Container<int> intContainer(10);
Container<Package> packageContainer(10);
packageContainer.set(1, Package(100));
std::cout << packageContainer.get(1) << std::endl;
}
```