weixin_43113933 2020-05-09 17:08 采纳率: 58.3%
浏览 137
已采纳

c++对象返回值一个细节问题。。。

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

}
时返回对象,此时又成功调用了拷贝构造,我被这个整懵了,求解

  • 写回答

1条回答 默认 最新

  • dabocaiqq 2020-09-25 17:47
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已采纳回答 9月25日

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛