要求定义一类A,其有私有成员name(string类型)及其他成员。请完成类A的定义,使得类A只能被实例化为唯一的一个对象。 本题已经完成main函数编写如下,请提交其他相应代码(头文件引用部分,命名空间引用部分,类定义部分): int main() { string name1,name2; cin >> name1; cin >> name2; A* o1 = A::GetObject(name1); o1->Print(); A* o2 = A::GetObject(name2); o2->Print(); if (o1 == o2) { cout << "o1与o2指向的是同一个对象!" << endl; } delete o1; return 0; }
时间: 2024-01-14 13:04:06 浏览: 15
以下是类A的定义部分:
```cpp
#ifndef A_H
#define A_H
#include <string>
using std::string;
namespace UniqueObject {
class A {
private:
string name;
static A* instance;
A(string n) : name(n) {}
public:
void Print() {
std::cout << "Name: " << name << std::endl;
}
static A* GetObject(string n) {
if (instance == nullptr) {
instance = new A(n);
}
return instance;
}
static void ReleaseObject() {
if (instance != nullptr) {
delete instance;
instance = nullptr;
}
}
};
A* A::instance = nullptr;
}
#endif // A_H
```
其中,我们通过定义一个`static`的私有成员`instance`来确保`A`类只能被实例化为唯一的一个对象。在`GetObject`函数中,如果`instance`还没有被实例化,则通过`new`关键字生成一个新的`A`类实例,并将其赋值给`instance`成员;否则直接返回`instance`成员。`ReleaseObject`函数可以用于释放该唯一实例,其内部实现是通过`delete`关键字释放`instance`实例,并将其置为`nullptr`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)