当使用"="定义对象时,复制构造函数不起作用.运算符(复制初始化)? [英] The copy-constructor doesn't work when defines an object with "=" operator(Copy-initialization)?

查看:59
本文介绍了当使用"="定义对象时,复制构造函数不起作用.运算符(复制初始化)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

#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?

推荐答案

您的代码只需要默认构造函数,因为您将char*作为初始化参数.您需要传递对象以获取副本构造函数和= op才能被调用.试试这个:
Your code only requires the default constructors as you are passing char*s as intialisation parameters. You need to pass objects to get the copy constructor and =op to be invoked. Try this:
String mystr2;
mystr2 = mystr1;
String mystr3(mystr2);


mystr1是不带参数的.因此,将调用默认构造函数String().此外,没有为char *定义复制操作.您可以添加以下内容:
mystr1 is constructed without parameter. So the default constructor String() is called. Additionally, there is no copy operation defined for char* You may add this:
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.


构造函数是隐式转换器,

Constructors are implicit converters,

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.


这篇关于当使用"="定义对象时,复制构造函数不起作用.运算符(复制初始化)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆