gpt4 book ai didi

c++ - 类模板上的运算符重载

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:03 32 4
gpt4 key购买 nike

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

template <class T>
class MyClass {
// ...
};
  • 运算符+=

    // 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'
  • 运营商<<

    // 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

我在这里做错了什么?

最佳答案

您需要说明以下内容(因为您与整个模板 成为 friend ,而不仅仅是它的特化,在这种情况下,您只需要在 <> 之后添加一个 operator<< ) :

template<typename T>
friend std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

实际上,除非它访问private或protected成员,否则不需要将其声明为友元。由于您刚刚收到警告,看来您的友元声明不是一个好主意。如果你只是想将它的单一特化声明为友元,你可以像下面那样做,在你的类之前对模板进行前向声明,这样operator<<被识别为模板。

// before class definition ...
template <class T>
class MyClass;

// note that this "T" is unrelated to the T of MyClass !
template<typename T>
std::ostream& operator<<(std::ostream& out, const MyClass<T>& classObj);

// in class definition ...
friend std::ostream& operator<< <>(std::ostream& out, const MyClass<T>& classObj);

上面和这种方式都将它的特化声明为友元,但第一个将所有 特化声明为友元,而第二个只声明operator<< 的特化。作为一个 friend T等于 T授予友元的类(class)。

在另一种情况下,您的声明看起来没问题,但请注意您不能 +=一个MyClass<T>MyClass<U>什么时候TU与该声明的类型不同(除非您在这些类型之间进行隐式转换)。你可以让你的+=成员模板

// In MyClass.h
template<typename U>
MyClass<T>& operator+=(const MyClass<U>& classObj);


// In MyClass.cpp
template <class T> template<typename U>
MyClass<T>& MyClass<T>::operator+=(const MyClass<U>& classObj) {
// ...
return *this;
}

关于c++ - 类模板上的运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332688/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com