本文介绍了当使用"="定义对象时,复制构造函数不起作用.运算符(复制初始化)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
#include <iostream>
using namespace std;
class String
{
char name[256];
public:
String(char* str)
{
cout<<"Constructor" << endl;
strcpy(name,str);
}
String(String &s)
{
cout<< "Copy Constructor"<< endl;
strcpy(name,s.name);
}
String()
{
cout<<"Default Constructor"<<endl;
}
~String(){}
String& operator=(const String&s)
{
strcpy(name,s.name);
cout<<"Assign Operator"<<endl;
return *this;
}
void display()
{
cout << "The String is:" << name << endl;
}
};
int main()
{
String mystr1 = "a";//Why does it only print "Constructor"?
String mystr2;
mystr2 = "aa";
String mystr3("aaa");//Here just invoke String::String(char *str).
return 0;
}
为什么在定义"mystr1"时不调用String :: String(String& s)?
Why don''t invoke String::String(String &s) while defining "mystr1" ? How compiler deals with the mystr1 definition?
推荐答案
String mystr2;
mystr2 = mystr1;
String mystr3(mystr2);
String& operator=(const char* s)
{
ASSERT(s);
strncpy(name, s, 256);
name[255] = '\0';
cout<<"char* assign Operator"<<endl;
return *this;
}
CPallini是正确的,我的回答是错误的.
CPallini is right and my answer is wrong.
String mystr1 = "a";//Why does it only print "Constructor"?
is as good as (if you are using non explicit constructor taking char*)
String mystr1("a");//Why does it only print "Constructor"?
use explicit keyword and then try -
....
explicit String(char* str)
{
cout<<"Constructor" << endl;
strcpy(name,str);
}
....
String mystr1 = "a";// This won't compile now
// and no implicit conversions will take place.
此链接也将提供帮助.
This link will also help.
这篇关于当使用"="定义对象时,复制构造函数不起作用.运算符(复制初始化)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!