在C ++中的函数模板中使用重载的运算符+

时间:2018-03-30 16:32:01

标签: c++ function templates overloading operator-keyword

这是一项学校作业。我应该遵守使用重载运算符的要求,并且必须在名为"增加"的函数模板中调用它。 这是一个名为Inductor的类。

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

虽然这是我的功能模板&#34;增加&#34;。

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搜索和搜索了,但是我没有看到一篇文章,其中一个类的重载运算符+正在函数模板中使用。

1 个答案:

答案 0 :(得分:3)

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分配给intoperator +的返回类型),并且没有此类运算符。并且由于没有构造函数仅构建int来构建Inductor,因此复制分配不是替代方案。

第一个错误很容易修复,只需删除变量(return a + b;)或直接初始化它(FIRST c = a + b; return c;)。

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

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