#include
#include
using namespace std;
class Location
{
public:
//带参数的构造函数
Location(int xx =0,int yy =0)
{
X=xx;
Y=yy;
cout<<"Constructor Object."<<endl;
}
//copy构造函数完成对象的初始化
Location(const Location& obj)//copy构造函数
{
X=obj.X;
Y=obj.Y;
cout<<"Copy Constructor."<<endl;
}
~Location()
{
cout<<X<<","<<Y<<" Object destroyed." <<endl;
}
int GetX()
{
return X;
}
int GetY()
{
return Y;
}
private :
int X;
int Y;
};
Location g()
{
Location temp(1,2);
return temp;
}
void test1()
{
g();
}
void test2()
{
//用匿名对象初始化m,此时c++编译器直接把匿名对转成m;(扶正)从匿名转成有名字了m
//就是将这个匿名对象起了名字m,他们都是同一个对象
Location m= g();
printf("匿名对象会扶正,不会被析构掉 \n");
cout<<m.GetX()<<endl;;
}
void test3()
{
//用匿名对象赋值给m2后,匿名对象被析构
Location m2(1,2);
m2=g();
printf("因为用匿名对象=给m2,匿名对象被析构\n");
cout<<m2.GetX()<<endl;;
}
int main(void)
{
test1();
cout<<"---------------------"<<endl;
test2();
cout<<"---------------------"<<endl;
test3();
return 0;
}
这是网上的一道题,都说
Location g()
{
Location temp(1,2);
return temp;
}
这里返回对象时会调用拷贝构造函数,但这个例子中为什么有没有调用呢,没有打印Copy Constructor.
而另外一道题
#include
#include
using namespace std;
class String
{
private:
char str;
int len;
public:
String(const char s);//构造函数声明
String operator=(const String& another);//运算符重载,此时返回的是对象
void show()
{
cout << "value = " << str << endl;
}
/*copy construct*/
String(const String& other)
{
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
cout << "copy construct" << endl;
}
~String()
{
delete[] str;
cout << "deconstruct" << endl;
}
};
String::String(const char* s)//构造函数定义
{
len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
String String::operator=(const String &other)//运算符重载
{
if (this == &other)
return *this;
delete[] str;
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
return *this;
}
int main()
{
String str1("abc");
String str2("123");
String str3("456");
str1.show();
str2.show();
str3.show();
str3 = str1 = str2;//str3.operator=(str1.operator=(str2))
str3.show();
str1.show();
return 0;
}
//运行结果
value = abc
value = 123
value = 456
copy construct
copy construct
deconstruct
deconstruct
value = 123
value = 123
deconstruct
deconstruct
deconstruct
同样调用
String String::operator=(const String &other)//运算符重载
{
if (this == &other)
return *this;
delete[] str;
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
return *this;
}
时返回对象,此时又成功调用了拷贝构造,我被这个整懵了,求解