什么情况下会调用拷贝构造:
1、使用旧对象给新对象赋值时
User user1 = user;
2、使用对象当作函数的参数,当调用函数时,就会一起调用拷贝构造。
#include <iostream>
#include <cstring>
using namespace std;
class User
{
char* name;
char pass[7];
int id;
public:
User(const char* name,const char* pass)
{
this->name = new char[strlen(name)+1];
strcpy(this->name,name);
strcpy(this->pass,pass);
}
void show(void)
{
cout<<name <<" " <<pass <<endl;
}
~User(void)
{
cout<<"析构"<<&name <<endl;
delete[] name;
}
User(User& that)
{
name = new char[strlen(that.name)];
strcpy(name,that.name);
strcpy(pass,that.pass);
cout << "我是拷贝构造" << endl;
}
};
void func(User& user)
{
user.show();
}
int main()
{
User u1("a","aa");
u1.show();
// 调用拷贝构造
User u2 = u1;
u2.show();
func(u1);
}
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!