异常原因#include <iostream> #include<memory> #include<string> using namespace std; class Product { public: virtual void Creat() = 0; }; class ProductA : public Product { public: void Creat() { cout << "创建产品A"; }; }; class ProductB : public Product { public: void Creat() { cout << "创建产品B"; } }; class Factory { public: virtual void makeProduct() = 0; void setProduct(char type_of_product) { if (type_of_product == 'a'){ unique_ptr<Product> productA = make_unique<ProductA>(); this->product = productA.get(); } }; protected: Product* product; }; class Factory1 : public Factory { public: void makeProduct() { cout << "工厂1:"; this->product->Creat(); } }; class Factory2 : public Factory { public: void makeProduct() { cout << "工厂2:"; this->product->Creat(); } }; int main() { unique_ptr<Product> productA = make_unique<ProductA>(); unique_ptr<Factory> factory1 = make_unique<Factory1>(); factory1->setProduct('A'); factory1->makeProduct(); return 0; }
时间: 2023-07-16 08:15:52 浏览: 63
这份代码中存在一些问题:
1. `Factory::setProduct()` 中只有对产品A的处理,没有对产品B的处理。
2. `Factory::product` 指针没有进行初始化,可能会导致程序崩溃。
3. `unique_ptr<Factory> factory1 = make_unique<Factory1>();` 中的 `Factory1` 类没有定义默认构造函数,因此需要手动提供一个构造函数。
以下是修改后的代码:
```
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Product {
public:
virtual void Creat() = 0;
};
class ProductA : public Product {
public:
void Creat() {
cout << "创建产品A";
};
};
class ProductB : public Product {
public:
void Creat() {
cout << "创建产品B";
}
};
class Factory {
public:
virtual void makeProduct() = 0;
virtual ~Factory() {}
void setProduct(char type_of_product) {
if (type_of_product == 'a') {
unique_ptr<Product> productA = make_unique<ProductA>();
this->product = productA.get();
}
else if (type_of_product == 'b') {
unique_ptr<Product> productB = make_unique<ProductB>();
this->product = productB.get();
}
};
protected:
Product* product = nullptr;
};
class Factory1 : public Factory {
public:
Factory1() {}
void makeProduct() {
cout << "工厂1:";
if (product) {
product->Creat();
}
else {
cout << "未设置产品" << endl;
}
}
};
class Factory2 : public Factory {
public:
Factory2() {}
void makeProduct() {
cout << "工厂2:";
if (product) {
product->Creat();
}
else {
cout << "未设置产品" << endl;
}
}
};
int main() {
unique_ptr<Factory> factory1 = make_unique<Factory1>();
factory1->setProduct('a');
factory1->makeProduct();
return 0;
}
```
修改后的代码中,`Factory::setProduct()` 中加入了对产品B的处理;`Factory::product` 指针进行了初始化;`Factory1` 和 `Factory2` 中分别添加了默认构造函数并且在 `makeProduct()` 中判断是否设置了产品。
阅读全文