【问题标题】:Assignement and addition overload for template objects模板对象的赋值和加法重载
【发布时间】:2021-12-29 18:25:15
【问题描述】:

我正在尝试同时学习模板和重载。我已经编写了下面的代码,但我无法使用内置类型分配数据对象。我做错了什么以及如何解决它,更好的是什么是可以导致不调用中间复制构造函数的最佳实践?

我想要所有可能的算术运算。我认为,如果我对其中一个(例如 +)做对了,那么其他人将是相同的原则。

我需要复制/移动构造函数和赋值吗?

#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

}

Compile Explorer Link

【问题讨论】:

  • 您不能仅通过返回类型为 void operator=(const T& t) 和 Data operator=(const T& t) 来重载运算符

标签: c++ templates operator-overloading c++20


【解决方案1】:

对于初学者,您不能仅通过返回类型来重载运算符

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;
    }
};

【讨论】:

  • 谢谢!重载的返回限定符不应该是const
  • @DEKKER 例如,对于运算符 +,返回类型可以有限定符 const。
【解决方案2】:

问题是您同时定义了void operator=(const T&amp; t)Data operator=(const T&amp; t)。 C++ 不允许两个函数仅在返回类型上有所不同,因为无法确定何时应该调用哪个重载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-04
    • 2011-08-03
    • 2014-07-06
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多