我正在嘗試同時學習模板和多載。我已經撰寫了下面的代碼,但我無法使用內置型別分配資料物件。我做錯了什么以及如何解決它以及更好的最佳實踐是什么可以導致沒有中間復制建構式被呼叫?
我想要所有可能的算術運算。我認為如果我為其中之一(例如 )做對了,那么其他人將遵循相同的原則。
我需要復制/移動建構式和賦值嗎?
#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
}
編譯資源管理器鏈接
uj5u.com熱心網友回復:
對于初學者,您可能不會僅通過回傳型別多載運算子
void operator=(const T& t) {
this->d = t;
}
Data operator=(const T& t) { // FAIL
return Data(this->d t);
}
至于其他問題,則在此宣告中
d = c 1;
由于運算子的宣告,運算式c 1具有回傳型別void
void operator (const T& other) {
this->d = other;
}
應該像這樣宣告和定義運算子
Data operator (const T& other) const
{
return this->d other;
}
運算子可以多載,如下所示
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;
}
Data operator ( const T &other ) const {
return this->d other;
}
Data operator ( const Data &other ) const {
return this->d other.d;
}
Data & operator =( const Data &other ) {
this->d = other.d;
return *this;
}
Data & operator=( const T &t ) {
this->d = t;
return *this;
}
};
uj5u.com熱心網友回復:
問題是您已經定義了void operator=(const T& t)和Data operator=(const T& t)。C 不允許兩個函式僅因回傳型別而不同,因為無法確定何時應呼叫哪個多載。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397254.html
上一篇:在Xamarin中關閉子表單后觸發Mainpage的功能
下一篇:默認成員值初始化在GCC中被忽略
