c++中的显式运算符+
explicit operator + in C++
我只是在玩+运算符&我不知道如何声明它并"显式地"使用它请帮助代码如下:
class compex{
int real;
int img;
public:
compex();
compex(int,int);
compex& explicit operator + (const compex& P1)
friend ostream& operator <<(ostream& out,const compex& R);
};
,操作符的实现为:
compex& compex :: operator + (const compex& P1)
{
this->real += P1.real;
this->img += P1.img;
return *this;
}
您不能将(这些)操作符设置为explicit
(只有转换操作符可以在c++ 11中显式设置)。你不需要这么做。只需避免显式转换到您的类型,通过:
- 没有定义其他类型的转换操作符,并且…
- 标记所有可以用一个参数
explicit
调用的复合函数。
这样,您可以有效地只使用已经是complex
的类型调用operator+
。
显式关键字仅对具有一个参数的构造函数有用。它将阻止编译器使用该构造函数进行转换。我不知道你让+运算符显式是想要达到什么目的。:)
如果您想要一个explicit
转换函数,您将不得不为此目的编写一个(见这里)(但它只能使用一个参数)。
至于你的operator+(...)
,只要删除explicit
,它应该工作。
Compex c1(1,2);
Compex c2(3,12);
Compex c3 = c1 + c2;
如果您希望在使用operator +
时防止类型隐式转换为compex
,您可以利用模板参数。
模板形参不直接服从类型转换规则。
class compex{
template<class C,
typename std::enable_if<std::is_same<C,complex>::value>::type >
compex& operator + (const C& P1)
{
// Your code
}
};
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<