【发布时间】:2021-12-29 18:25:15
【问题描述】:
我正在尝试同时学习模板和重载。我已经编写了下面的代码,但我无法使用内置类型分配数据对象。我做错了什么以及如何解决它,更好的是什么是可以导致不调用中间复制构造函数的最佳实践?
我想要所有可能的算术运算。我认为,如果我对其中一个(例如 +)做对了,那么其他人将是相同的原则。
我需要复制/移动构造函数和赋值吗?
#include <iostream>
#include <concepts>
template<typename T>
requires std::is_arithmetic_v<T>
class Data {
private :
T d;
public:
Data(const T& data) : d{data}{
std::cout << "Constructed Data with: " << d << std::endl;
}
Data(const Data& other) = default;
~Data() {
std::cout << "Destructed: " << d << std::endl;
}
void operator+(const T& other) {
this->d += other;
}
Data operator+(const Data& other) {
return (this->d + other.d);
}
Data operator=(const Data& other) {
return(Data(d + other.d));
}
void operator=(const T& t) {
this->d += t;
}
Data operator=(const T& t) { // FAIL
return Data(this->d + t);
}
};
int main() {
Data a = 1;
Data b = 2;
Data c = a + b;
Data d = 10;
d = c + 1; // how to do this? FAIL
}
【问题讨论】:
-
您不能仅通过返回类型为 void operator=(const T& t) 和 Data operator=(const T& t) 来重载运算符
标签: c++ templates operator-overloading c++20