操作员 左右超载
operator+ overload left and right
我想超载操作员 在两边工作。当我使用操作员 时,我想将元素推入类的向量。这里是我的代码:
template<typename TElement>
class grades {
private:
vector<TElement> v;
public:
grades& operator+(const int& a) {
v.push_back(a);
return *this;
}
grades& operator=(const grades& g) {
v = g.v;
return *this;
}
friend grades& operator+(const int& a,const grades& g) {
//here i get some errors if i put my code
return *this;
}
};
int main() {
grades<int> myg;
myg = 10 + myg; // this operation i want
myg = myg + 9; //this work
return 0;
}
operator+
表示复制。operator+=
意味着一个就地突变。
这可能更惯用:
#include <vector>
using namespace std;
template<typename TElement>
class grades {
private:
vector<TElement> v;
public:
grades& operator+=(int a)
{
v.push_back(a);
}
// redundant
// grades& operator=(const grades& g) {
// v = g.v;
// return *this;
// }
friend grades operator+(grades g, const int& a) {
g += a;
return g;
}
friend grades operator+(const int& a,grades g) {
g.v.insert(g.v.begin(), a);
return g;
}
};
int main() {
grades<int> myg;
myg = 10 + myg; // this now works
myg = myg + 9; //this work
return 0;
}
操作员 应返回副本
template<typename TElement>
class grades {
private:
vector<TElement> v;
public:
grades operator+(const TElement& a) const {
grades ret(*this);
ret.v.push_back(a);
return ret;
}
friend grades operator+(const TElement& a,const grades& g) {
return g+a;
}
};
int main() {
grades<int> myg;
myg = 10 + myg; // this operation i want
myg = myg + 9; //this work
return 0;
}
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 寻找地理和伤害意味着超载
- 没有可行的超载'='用于shared_ptr
- "专业化不参与超载"
- 虚拟超载运算符>>和<<
- 不使用与左右停止工作命名空间 std 的简单比较
- 为什么我的超载"+"运算符返回的总额错误?
- C++ 超载 += 用于两个袋子的合并,返回类型为空隙
- C++11 中对超载'ref(Select::Expressions::Code&)'的调用模棱两可
- 如何在同一行上格式化左右对齐?
- 为什么STD :: SPAN超载函数调用操作员索引
- C 操作员超载调用驱动器
- C const char *评估操作员超载
- 如何包括C 模板类的非成员运算符 - 超载
- 类型长的长度和未解决的超载函数类型的类型的操作数与二进制运算符
- 无法调用纯抽象基类超载
- 二进制超载操作员=
- 操作员超载;必须是二进制操作员(具有3个参数)
- 如果我具有调用其其他实例之一的超载函数,它是否被认为是递归功能
- 操作员 左右超载