我正在审查 C++ 中的运算符重载。只是为了好玩,我正在实施一个BigInt
课程。
我要为其重载的第一个运算符是加法运算符。我决定将此运算符重载为友元非成员函数。这是此代码的 MWE:
#include <cassert>
#include <iostream>
#include <string>
class BigInt{
public:
friend BigInt operator+(const BigInt &bi1, const BigInt &bi2);
BigInt() {}
explicit BigInt(const std::string &in) {
if (in.size() != 0) {
for (auto cc = in.rbegin(); cc != in.rend(); ++cc) {
value_.push_back(*cc);
}
}
}
std::string value() {
std::string actual_value{}; // Reversed string.
for (auto cc = value_.rbegin(); cc != value_.rend(); ++cc) {
actual_value.push_back(*cc);
}
return actual_value;
}
private:
std::string value_; // String of digits as characters.
};
BigInt operator+(const BigInt &bi1, const BigInt &bi2) {
BigInt result{};
result.value_ = "4421";
return result;
}
int main() {
std::cout << "Test addition operator... ";
std::string number{"1234"}; // Number 1,234.
BigInt mm(number);
std::string number_ten{"10"}; // Number 10.
BigInt nn(number_ten);
BigInt mm_nn = mm + nn;
std::string expected_result{"1244"}; // 1,234 + 10 = 1,244.
assert(mm_nn.value() == expected_result);
std::cout << "ok." << std::endl;
}
这段代码模拟了加法的行为。它编译并运行。然而,当我为该类添加一个复制构造函数时BigInt
,此代码停止工作。即,如果我将其添加到类声明中:
explicit BigInt(const BigInt &in): value_(in.value_) {}
代码甚至无法编译。编码的加法函数返回构造的实例的副本BigInt
。为此,必须定义一个复制构造函数。如果我自己没有定义它,那么编译器会这样做。编译器会产生什么我没有通过添加的复制构造函数产生?这是我得到的编译错误:
$ g++ -std=c++14 -g mwe.cpp
mwe.cpp: In function ‘BigInt operator+(const BigInt&, const BigInt&)’:
mwe.cpp:34:10: error: no matching function for call to ‘BigInt::BigInt(BigInt&)’
return result;
^
mwe.cpp:9:3: note: candidate: BigInt::BigInt()
BigInt() {}
^
mwe.cpp:9:3: note: candidate expects 0 arguments, 1 provided
mwe.cpp: In function ‘int main()’:
mwe.cpp:44:23: error: no matching function for call to ‘BigInt::BigInt(BigInt)’
BigInt mm_nn = mm + nn;
^
mwe.cpp:9:3: note: candidate: BigInt::BigInt()
BigInt() {}
^
mwe.cpp:9:3: note: candidate expects 0 arguments, 1 provided
从它看来,编译器似乎需要一个我没有提供的复制构造函数。现在...如果我删除explicit
关键字,一切正常。但是,我已经看到了具有显式复制构造函数的实现,例如:Explicit copy constructor
我错过了什么?为什么我不能在重载加法运算符时使这个复制构造函数显式?一般来说,复制构造函数应该显式吗?