操作员必须采取"无效"
Operator must take 'void'
>假设我有两个类:
// A struct to hold a two-dimensional coordinate.
struct Point
{
float x;
float y;
};
// A struct identical to Point, to demonstrate my problem
struct Location
{
float x;
float y;
};
我想隐式地将Location
转换为Point
:
Point somePoint;
Location someLocation;
somePoint = someLocation;
因此,我在Point
中添加了此operator
:
operator Point(Location &other)
{
// ...
}
在此基础上,我在 Debian 上使用 g++ 4.9.2
进行编译,并收到此错误:
error: 'Point::operator Point(Location &other)' must take 'void'
听起来编译器希望运算符不接受任何参数,但这似乎不对 - 除非我错误地使用了运算符。此错误背后的真正含义是什么?
用户定义的转换运算符定义为要从中转换为其他类型的类型的成员函数。签名是(在类Location
内部):
operator Point() const; // indeed takes void
// possibly operator const& Point() const;
另一种可能性是为Point
提供一个转换构造函数:
Point(Location const& location);
不要重载运算符()。您要做的是创建一个获取点的自定义构造函数。编译器在执行赋值或重载赋值运算符时调用此函数。
Location( Point& p){
x = p.x;
y = p.y;
}
Location& operator= ( Point& p){
x = p.x;
y = p.y;
return *this;
}
这将得到这个编译
Point somePoint;
Location someLocation;
somePoint = someLocation;
Location loc = somePoint;
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- <<操作员在下面的行中工作
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- FFMPEG配置文件级别id大小无效
- 错误:从"int"到枚举c++的转换无效
- 如何修复此错误:className::className的无效使用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- C++-模板嵌套类的引用初始化无效
- 错误:无效的预处理指令 #i 的意思是 #if?
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- 对操作员限制的代码挑战的无效解决方案
- 与操作员'<<'不匹配 有人可以帮助解决无效功能错误吗?[C++]
- 操作员必须采取"无效"
- munmap_chunk 当操作员调用时指针无效,然后调用 destroctor