相关疑难解决方法(0)

运算符重载类模板

我在为模板类定义一些运算符重载时遇到了一些问题.让我们以这个假设的类为例.

template <class T>
class MyClass {
  // ...
};
Run Code Online (Sandbox Code Playgroud)
  • 操作者+ =

    // 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    导致此编译器错误:

    no match for 'operator+=' in 'classObj2 += classObj1'
    
    Run Code Online (Sandbox Code Playgroud)
  • 运营商<<

    // 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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    结果在此编译器警告:

    friend declaration 'std::ostream& operator<<(std::ostream&, const MyClass<T>&)' …
    Run Code Online (Sandbox Code Playgroud)

c++ templates operator-overloading

14
推荐指数
3
解决办法
8万
查看次数

标签 统计

c++ ×1

operator-overloading ×1

templates ×1