gpt4 book ai didi

c++ - 在 C++ 的函数模板中使用重载的 operator+

转载 作者:行者123 更新时间:2023-11-30 02:20:32 25 4
gpt4 key购买 nike

这是一项学校作业。我应该遵守使用重载运算符的要求,并且必须在名为“increase”的函数模板中调用它。这是一个名为 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;
}

虽然这是我的函数模板“增加”。

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

with FIRST == Inductor 有几个问题:

  • FIRST c;:您尝试创建 Inductor,但没有默认构造函数。
  • c = a + b;:您尝试为 Inductor 分配一个 int(运算符的返回类型 +),并且没有这样的运算符。并且由于没有仅采用 int 来构建 Inductor 的构造函数,因此复制赋值不是替代方案。

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

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

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

关于c++ - 在 C++ 的函数模板中使用重载的 operator+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49577958/

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