問題描述
我在為模板類定義一些運算符重載時遇到了一些問題.讓我們以這個假設的類為例.
I'm having some problems defining some operator overloads for template classes. Let's take this hypothetical class for example.
template <class T>
class MyClass {
// ...
};
運算符+=
operator+=
// In MyClass.h MyClass<T>& operator+=(const MyClass<T>& classObj); // In MyClass.cpp template <class T> MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) { // ... return *this; }
導致此編譯器錯誤:
no match for 'operator+=' in 'classObj2 += classObj1'
運算符<<
operator<<
// In MyClass.h friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj); // In MyClass.cpp template <class T> std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj) { // ... return out; }
導致此編譯器警告:
friend declaration 'std::ostream& operator<<(std::ostream&, const MyClass<T>&)' declares a non-template function
我在這里做錯了什么?
推薦答案
// In MyClass.h MyClass<T>& operator+=(const MyClass<T>& classObj); // In MyClass.cpp template <class T> MyClass<T>& MyClass<T>::operator+=(const MyClass<T>& classObj) { // ... return *this; }
這對模板無效.運算符的完整源代碼必須在使用它的所有翻譯單元中.這通常意味著代碼內聯在標頭中.
This is invalid for templates. The full source code of the operator must be in all translation units that it is used in. This typically means that the code is inline in the header.
從技術上講,根據標準,可以導出模板,但是很少有編譯器支持它.此外,如果模板在 MyClass.cpp 中為所有 T- 類型顯式實例化,您也可以執行上述操作,但實際上,這通常無視模板的要點.
Technically, according to the Standard, it is possible to export templates, however very few compilers support it. In addition, you CAN also do the above if the template is explicitly instantiated in MyClass.cpp for all types that are T- but in reality, that normally defies the point of a template.
更多我通讀了你的代碼,它需要一些工作,例如重載運算符 [].此外,通常,我會將維度作為模板參數的一部分,允許在編譯時捕獲 + 或 += 的失敗,并允許有意義地堆棧分配類型.您的異常類還需要從 std::exception 派生.然而,這些都不涉及編譯時錯誤,它們只是不是很好的代碼.
More edit: I read through your code, and it needs some work, for example overloading operator[]. In addition, typically, I would make the dimensions part of the template parameters, allowing for the failure of + or += to be caught at compile-time, and allowing the type to be meaningfully stack allocated. Your exception class also needs to derive from std::exception. However, none of those involve compile-time errors, they're just not great code.
這篇關于類模板上的運算符重載的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!