在這段代碼中,我試圖為我的類制作一個模板,還有 2 個模板函式,一個用于標準型別,一個用于我的模板類,但我想看看我是否可以在模板中創建一個模板來獲得定義的函式(我不知道這是否是正確的方法)。最后,在我運行代碼后,它給了我一些奇怪的錯誤,比如語法錯誤等。感謝幫助!
#include <iostream>
template <typename T>
class Complex
{
T _re, _im;
public:
Complex(T re = 0, T im = 0) :_re{re}, _im{im} {};
~Complex() {}
Complex<T>& operator=(const Complex<T>& compl) { if (this == &compl) return *this; this._re = compl._re; this._im = compl._im; return *this; }
Complex<T> operator (const Complex<T>& compl) { Complex<T> temp; temp._re = _re compl._re; temp._im = _im compl._im; return temp}
friend std::ostream& operator<<(std::ostream& os, const Complex<T>& compl) { os << compl._re << " * i " << compl._im; return os; }
};
template <typename T>
T suma(T a, T b)
{
return a b;
}
template <template<typename> typename T, typename U>
void suma(T<U> a, T<U> b)
{
T<U> temp;
temp = a b;
std::cout << temp;
}
int main()
{
int a1{ 1 }, b1{ 3 };
std::cout << "Suma de int : " << suma<int>(a1, b1) << std::endl;
double a2{ 2.1 }, b2{ 5.9 };
std::cout << "Suma de double: " << suma<double>(a2, b2) << std::endl;
Complex<int> c1(3, 5), c2(8, 9);
std::cout << "Suma comple int: ";
suma<Complex, int>(c1, c2);
return 0;
}
uj5u.com熱心網友回復:
compl是一個 c 關鍵字(作為一元運算子的替代~)。您用作compl您的運算子多載引數。
幾分鐘前我還不知道這一點。我是怎么發現的?我將您的代碼粘貼到了Godbolt.org 中,它突出顯示了“compl”字樣,就好像它們是關鍵字一樣。后來上網一搜,果然是關鍵詞。
還有使用this._re = ...andthis._im = ...不起作用,因為它this是一個指標而不是一個參考,所以它應該this->_re = ...或者最好只是_re = ....
uj5u.com熱心網友回復:
您的程式中有 3 個錯誤。
首先,compl您可以使用其他名稱,而不是使用關鍵字,就像我在這里所做的那樣。
其次,您錯過了 上面代碼鏈接中修復的;after 陳述句return temp。
第三你正在使用
this._re = rhs._re;
this._im = rhs._im;
而正確的寫法是:
_re = rhs._re;//note the removed this.
_im = rhs._im;//note the removed this.
糾正這些錯誤后程式的作業原理可以看出這里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356497.html
上一篇:嘗試在新類中使用另一個類的方法時,我不斷收到位置引數錯誤
下一篇:PythonOOP方法呼叫
