在C 中的功能模板中使用过载的操作员
Using an overloaded operator+ within a function template in C++
这是用于学校作业的。我应该遵守使用超载运算符的要求,必须在称为"增加"的函数模板中调用。这是一个称为电感器的类。
#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 +
的返回类型(,并且没有此类操作员。而且由于没有构造函数仅用于构建Inductor
的int
,因此复制分配不是替代方案。
第一个错误很容易解决,只需摆脱变量(return a + b;
(或直接初始化它(FIRST c = a + b; return c;
(。
对于第二个错误,添加一个(非显式(构造函数仅次int
或更改operator+
直接返回Inductor
:
Inductor Inductor::operator+(int add)
{
return Inductor(inductance + add, maxCurrent);
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 需要帮助操作员过载,这样我才能显示功能
- 操作员<<如何使用机械手功能
- 操作员比功能快
- 带有成员(操作员[])功能的Indoke_Result
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用
- 在C 中的功能模板中使用过载的操作员
- 如何使用Sfinae为容器创建模板功能,并根据操作员推断返回类型
- 任何操作员,功能调用和构造函数的通用持续时间表
- 如果功能超载,则BOOST PHOENIX成员功能操作员无法编译
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 操作员过载功能
- 在C 中使用功能作为操作员过载
- C++过载+操作员友情功能
- 如何使用此独特的操作员重载功能
- 过载操作员功能失败
- 与操作员'<<'不匹配 有人可以帮助解决无效功能错误吗?[C++]
- 没有操作员发现升压read_xml功能错误
- 操作员重新分配功能/结构返回什么
- 使用操作员<<的记录功能