[英]What happens when value is passed to operator overloader function in C++?
I failed to understand the steps of compilation of this code.我没看懂这段代码的编译步骤。 First, where is what is purpose of the default constructor, and why so many objects of type MyClass?首先,默认构造函数的目的是什么,为什么有这么多 MyClass 类型的对象? link to sololearn where I saved the code链接到我保存代码的sololearn
#include <iostream>
using namespace std;
class MyClass {
public:
int var;
MyClass() { }
MyClass(int a)
: var(a) { }
MyClass operator+(MyClass &obj) {
MyClass res;
res.var= this->var+obj.var;
//'this' is refering to active (obj1)
return res;
}
};
int main() {
MyClass obj1(12), obj2(55);
MyClass res = obj1+obj2;
cout << res.var;
}
//I've not understood, its from a lesson
If you suspect you don't need a piece of code, try compiling without it and you'll know pretty quickly whether your suspicion was correct or not.如果您怀疑自己不需要一段代码,请尝试不使用它进行编译,您很快就会知道您的怀疑是否正确。
When you remove the default constructor in the class you provided here's what happens:当您删除 class 中的默认构造函数时,您在此处提供了以下内容:
..\Playground\: In member function 'MyClass MyClass::operator+(MyClass&)':
..\Playground\:11:21: error: no matching function for call to 'MyClass::MyClass()'
MyClass res;
^~~
..\Playground\:7:9: note: candidate: MyClass::MyClass(int)
MyClass(int a)
^~~~~~~
..\Playground\:7:9: note: candidate expects 1 argument, 0 provided
..\Playground\:4:7: note: candidate: constexpr MyClass::MyClass(const MyClass&)
class MyClass {
Which is to say the problem is in the +operator implementation at the line MyClass res;
也就是说,问题出在MyClass res;
行的 +operator 实现中。 . . This line creates an instance of the object MyClass
using the default constructor, so there's no way the code snippet your provided works without a default constructor.此行使用默认构造函数创建 object MyClass
的实例,因此如果没有默认构造函数,您提供的代码片段将无法工作。
The constructor without parameters is for the object that doesn't pass any value, the one that stores the sum of the two operand objects.不带参数的构造函数用于不传递任何值的 object,即存储两个操作数对象之和的值。 ---simple--- - -简单的 - -
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.