gpt4 book ai didi

c++ - 如果是 Singleton 类,我应该如何编写复制构造函数,我应该如何重载 = 运算符?

转载 作者:太空狗 更新时间:2023-10-29 23:24:59 24 4
gpt4 key购买 nike

我应该如何为我的单例类编写一个复制构造函数以防止创建一个新对象,因为我已经有一个。重载 = 运算符的最佳做法是什么

 #include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;

class Rect
{
int length;
int breadth;
static int count;
static int maxcount;
Rect()
{};
Rect(const Rect& abc){};
public :

~Rect();
int area_rect()
{return length*breadth;}
void set_value(int a,int b);

static Rect* instance()
{
Rect* ptr=NULL;
if(count < maxcount)
{
ptr=new Rect ;
count++;
}
return ptr;
}
};
int Rect::count = 0;
int Rect::maxcount = 1;
void Rect::set_value(int a,int b)
{
length=a;
breadth=b;
}
Rect::~Rect()
{
count --;
}
int main()
{
Rect* a= Rect::instance(); //creates first object
// Rect* c= Rect::instance(); //fails to create second object
//as maxcount=1 and returns NULL
a->set_value(10,3);
cout << "area realted to object a : " << a->area_rect() <<"\n";
Rect* b=a;//allows creation of second object which I dont want
b->set_value(10,4);
cout << "area realted to object b : " << b->area_rect() <<"\n";
delete a;
delete b;
getch();
return 0;
}

如何编写复制构造函数代码并重载相等运算符以防止创建更多对象?

最佳答案

要么按照此处的说明使其不可复制

How do I make this C++ object non-copyable?

或者您定义复制构造函数和赋值运算符,以便获得相同的单例。取决于您实际需要的功能。

分配通常也应该被禁止(如上面的链接所示):

class Rect{
Rect( const Rect& ) = delete;
Rect& operator=( const Rect& ) = delete;
. . .
}

这也禁止移动操作。

您可能还想知道: Are Singletons really that bad?

关于c++ - 如果是 Singleton 类,我应该如何编写复制构造函数,我应该如何重载 = 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com