在C 中的功能模板中使用过载的操作员

Using an overloaded operator+ within a function template in C++

本文关键字:操作员 功能      更新时间:2023-10-16

这是用于学校作业的。我应该遵守使用超载运算符的要求,必须在称为"增加"的函数模板中调用。这是一个称为电感器的类。

#pragma once
#include <iostream>
using namespace std;
class Inductor {
    friend ostream& operator<<(ostream&, Inductor);
private:
    int inductance;
    double maxCurrent;
public: 
    int operator+(int add);
    int operator-(int sub);
    Inductor(int, double);
};
Inductor::Inductor(int x, double y)
{
    inductance = x;
    maxCurrent = y;
}

int Inductor::operator+(int add)
{
    int newSum = inductance + add;
    return newSum;
}
int Inductor::operator-(int sub)
{
    int newDiff = inductance - sub;
    return newDiff;
}
ostream& operator<<(ostream& out, Inductor inductor)
{
    out << "Inductor parameters: " << inductor.inductance << ", " << inductor.maxCurrent << endl;
    return out;
}

这是我的功能模板"增加"。

template<class FIRST>
FIRST increase(FIRST a, int b) {
    FIRST c;
    c = a + b;
    return c;
}

最后但并非最不重要的一点是,我的主要文件:

int main()
{
    Inductor ind(450, 0.5);
    ind = increase(ind, 70);
}

这些是以下我不理解的汇编错误:

error C2512: 'Inductor': no appropriate default constructor available
error C2679: binary '=': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
note: could be 'Inductor &Inductor::operator =(Inductor &&)'
note: or       'Inductor &Inductor::operator =(const Inductor &)'
note: see reference to function template instantiation 'FIRST increase<Inductor>(FIRST,int)' being compiled
    with
    [
        FIRST=Inductor
    ]
note: see declaration of 'Inductor'

任何人都可以介意解释为什么编译器会抛出这些错误?是的,我已经通过StackoverFlow进行了搜索并搜索了搜索,但是我看不到一篇文章,该文章在函数模板中使用了从类中使用的超载运算符 。

template<class FIRST>
FIRST increase(FIRST a, int b) {
    FIRST c;
    c = a + b;
    return c;
}

使用FIRST == Inductor有几个问题:

  • FIRST c;:您尝试创建Inductor,而没有默认的构造函数。
  • c = a + b;:您尝试将Inductor分配给CC_6( operator +的返回类型(,并且没有此类操作员。而且由于没有构造函数仅用于构建Inductorint,因此复制分配不是替代方案。

第一个错误很容易解决,只需摆脱变量(return a + b;(或直接初始化它(FIRST c = a + b; return c;(。

对于第二个错误,添加一个(非显式(构造函数仅次int或更改operator+直接返回Inductor

Inductor Inductor::operator+(int add)
{
    return Inductor(inductance + add, maxCurrent);
}