提问人:user3395789 提问时间:5/23/2023 最后编辑:Jerry Coffinuser3395789 更新时间:5/24/2023 访问量:180
查询 C++ 中的复制构造函数和赋值运算符
Query about Copy Constructor and Assignment operator in C++
问:
我正在尝试重载字符串类。在下面显示的代码中,我希望只调用重载的 Assignment 运算符,但也调用重载的复制构造函数。 如果我的代码有错误或我的理解不同,任何人都可以建议吗?
#include<iostream>
using namespace std;
class String_Overload{
char *s_ptr;
public:
String_Overload()
{
s_ptr = new char(1);
s_ptr[0]='\0';
cout<<"In no param constructor"<<"\n";
}
String_Overload(const char* s_ptr_cpy)
{
int len=0;
while(s_ptr_cpy[len]!=NULL)
{++len;}
s_ptr = new char(len+1);
for(int i=0;i<len;i++)
{
s_ptr[i]=s_ptr_cpy[i];
}
s_ptr[len+1]='\0';
cout<<"In overloaded constructor"<<"\n";
}
String_Overload(const String_Overload& s_ptr_cpy)
{
int len=0;
while(s_ptr_cpy.s_ptr[len]!=NULL)
{++len;}
s_ptr = new char(len+1);
for(int i=0;i<len;i++)
{
s_ptr[i]=s_ptr_cpy.s_ptr[i];
}
s_ptr[len+1]='\0';
cout<<"In copy constructor"<<"\n";
}
String_Overload operator=(String_Overload& s_ptr_cpy)
{
int len=0;
while(s_ptr_cpy.s_ptr[len]!=NULL){++len;}
for(int i=0;i<len;i++)
{
s_ptr[i]=s_ptr_cpy.s_ptr[i];
}
s_ptr[len+1]='\0';
cout<<"In assignment constructor\n";
return *this;
}
void display(){cout<<s_ptr<<"\n";}
~String_Overload(){delete []s_ptr;}
};
int main()
{
char temp[]="Hello World";
String_Overload s1{temp};
String_Overload s4;
s4=s1;
s4.display();
return 0;
}
输出:
In overloaded constructor
In no param constructor
In assignment constructor
In copy constructor
Hello World
答:
2赞
user12002570
5/24/2023
#1
我希望只调用重载的 Assignment 运算符,但也调用重载的复制构造函数
这是因为示例中的赋值按值返回。operator=
您可以通过将返回类型更改为,以便它按引用返回来解决此问题,如下所示:String_Overload&
//-------------v--------------------------------------->added & so that we return by reference
String_Overload& operator=(String_Overload& s_ptr_cpy)
{
//....
return *this;
}
我还建议阅读什么是赋值运算符的返回类型?
评论
new char(len+1)
char
len + 1
new char[en+1]
operator=
String_Overload& operator=(String_Overload&)
String_Overload& operator=(String_Overload s_ptr_cpy) { std::swap(s_ptr_cpy.s_ptr, s_ptr); return *this; }
delete
NULL
nullptr
std::strdup
std::free
new
delete
new char[N]