gpt4 book ai didi

C++ 运算符重载

转载 作者:IT老高 更新时间:2023-10-28 22:22:54 24 4
gpt4 key购买 nike

为什么下面的C++程序输出“ACCA”?为什么operator int()被调用了两次?

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

using namespace std;

class Base {
public:
Base(int m_var=1):i(m_var){
cout<<"A";
}
Base(Base& Base){
cout<<"B";
i=Base.i;
}
operator int() {
cout<<"C";
return i;
}
private:
int i;
};

int main()
{
Base obj;
obj = obj+obj;
return 0;
}

最佳答案

首先,这一行:

Base obj;

默认构造对象 obj,方法是选择接受整数的构造函数,默认值为 1。这负责将第一个 A 打印到标准输出。

那么,这个表达式:

obj + obj

需要选择一个可行的 operator + 重载。在这种情况下,由于 obj 有一个用户定义的到 int 的转换,内置的 operator + 被选中,两个参数都被转换到 int。这负责将两个 C 打印到标准输出。

然后,给obj赋值:

obj = obj + obj

需要为Base 调用隐式生成的operator =。隐式生成的 operator = 有签名:

Base& operator = (Base const&);

这意味着等号右侧的表达式,类型为 int,必须转换为临时 Base 对象, obj 被赋值(隐式生成的 operator = 的引用参数绑定(bind)到这个临时值)。

但是从 int 创建这个临时文件又需要调用 Base 的转换构造,该构造再次接受 int,即负责将第二个 A 打印到标准输出。

关于C++ 运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17049320/

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