gpt4 book ai didi

C++ 覆盖赋值运算符

转载 作者:行者123 更新时间:2023-11-30 04:12:49 25 4
gpt4 key购买 nike

为了理解构造函数和赋值,我写了一个非常简单的测试代码,如下所示:

class A {
public:
A() { std::cout<<"This is default cstr."; }
A(int i) { std::cout<<"This is int cstr. value is "<<i; }
A(const A &a) { std::cout<<"This is copy cstr."; }
A operator=(const A &a) { std::cout<<"This is assignment operator."; return *this;// this line is tricky }
};
int _tmain(int argc, _TCHAR* argv[]) {
std::cout<<"line 1 "; A a1; std::cout<<std::endl;
std::cout<<"line 2 "; A a2 = A(1); std::cout<<std::endl;
std::cout<<"line 3 "; a1 = a2; std::cout<<std::endl;
return 0;
}

对于第 3 行,我得到:

line 3 This is assignment operator.This is copy cstr.

但是如果我将 return *this; 更改为 return NULL,我得到:

line 3 This is assignment operator.This is int cstr. value is 0

有人可以为我解释一下里面发生了什么吗?

最佳答案

您的运营商正在返回 A 而不是 A&:

A operator=(const A &a)

因此,当您返回 NULL 时,您正在调用隐式构造函数 A(int) 并将 NULL 传递给它。

关于C++ 覆盖赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672668/

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