gpt4 book ai didi

C++ 运算符重载和复制构造函数

转载 作者:可可西里 更新时间:2023-11-01 18:37:12 26 4
gpt4 key购买 nike

我很难理解以下内容(特别是场景 b):(假设我已经定义了一个赋值运算符、加法运算符和复制构造函数,只是为了输出它们被调用的事实)

场景一:

Simple a;
Simple b;
Simple c = a + b;

The output is as follows:
Simple constructor called
Simple constructor called
Simple add operator call
Simple constructor called
copy constructor called

-- 这一切都很好,花花公子

场景b(我无法理解的行为):

Simple d;
Simple e;
Simple f;
f = d + e;

Simple constructor called
Simple constructor called
Simple constructor called
Simple add operator called
Simple constructor called
copy constructor called
assignment operator called

我的问题是,在场景 b 中,为什么在赋值运算符之前调用复制构造函数?据我了解,复制构造函数只会在未初始化的对象上调用。但是,在这种情况下,对象 f 已在添加之前的行中进行了初始化。

如有解释,将不胜感激。

很抱歉没有立即发布源代码(以及缺少缩进 - 我在复制到文本区域时遇到问题)。这就是它的所有简单性。我正在使用 Visual Studio 2005。不幸的是,我还不太熟悉它的工作原理,因此我无法指定传递给编译器的优化参数。

class Simple
{
public:
Simple(void);
Simple operator +(const Simple& z_Simple) const;
Simple& operator =(const Simple& z_Simple);
Simple(const Simple& z_Copy);
int m_Width;
int m_Height;
public:
~Simple(void);
};


#include "Simple.h"
#include <iostream>

using std::cout;
using std::endl;

Simple::Simple(void)
{
this->m_Height = 0;
this->m_Width = 0;
cout << "Simple constructor called" << endl;
}

Simple::Simple(const Simple& z_Copy)
{
cout << "copy constructor called" << endl;
this->m_Height = z_Copy.m_Height;
this->m_Width = z_Copy.m_Width;
}

Simple& Simple::operator =(const Simple &z_Simple)
{
cout << "assignment operator called" << endl;
this->m_Height = z_Simple.m_Height;
this->m_Width = z_Simple.m_Width;
return *this;
}


Simple Simple::operator +(const Simple &z_Simple) const
{
cout << "Simple add operator called" << endl;
int y_Height = this->m_Height + z_Simple.m_Height;
int y_Width = this->m_Width + z_Simple.m_Width;
Simple y_Ret;
y_Ret.m_Height = y_Height;
y_Ret.m_Width = y_Width;
return y_Ret;
}

Simple::~Simple(void)
{
cout << "destructor called" << endl;
}

当然,Nemo 的解释是我的 C++ 新手可以理解的:)

将优化级别更改为/O2 后,我可以看到场景 b 的输出如下(以及我所期望的)

    Simple constructor called
Simple constructor called
Simple constructor called
Simple add operator called
Simple constructor called
assignment operator called

谢谢大家的建议。

最佳答案

您的 + 运算符按值返回一个对象,如果编译器没有 elide,这可能会导致调用复制构造函数 它。

Simple Simple::operator +(const Simple &z_Simple) const
{
//......
Simple y_Ret;
//......
return y_Ret;
}

代码:

Simple d;
Simple e;
Simple f;
f = d + e;

下面是一步一步的分析:

Simple constructor called     ---> creation of `d`
Simple constructor called ---> creation of `e`
Simple constructor called ---> creation of `f`
Simple add operator called ---> Inside Addition operator
Simple constructor called ---> creation of local `y_Ret`
copy constructor called ---> `y_Ret` returned by value
assignment operator called ---> Result returned by `+` used for `=`

关于C++ 运算符重载和复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com