使用用户定义的类型强制转换对象
casting object with user defined type
是否可以像处理普通数据类型那样使用用户定义类型强制转换对象?比如我们对int进行类型强制转换,比如:
int variable_one = (int)variable_name;
所以我们可以这样做:(complex) object_name;
其中complex是我使用operator+
重载为复数加法编写的类。
这是可能的吗?或者我们需要在调用这个语句之前写一些函数吗?还是根本不可能像这样进行类型强制转换?
int variable_one=(int)variable_name;
是C风格强制转换。
c++提供了许多类型转换操作符:
-
dynamic_cast <new_type> (expression)
-
reinterpret_cast <new_type> (expression)
-
static_cast <new_type> (expression)
-
const_cast <new_type> (expression)
看一看关于类型转换的文章,或者参考任何c++入门书籍
用户自定义类型强制转换操作符
交货)。
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
int x;
int y;
Point(int x, int y):x(x), y(y){}
operator int(){
return sqrt(x*x+y*y);
}
};
int main() {
Point point(10,10);
int x = (int)point;
cout << x ;
}
你为什么要这样做?我猜你应该写适当的构造函数,如果你想创建你的类的对象。如您所知,构造函数可以被重载。因此,如果需要以不同的方式构造对象,可以随意编写多个构造函数。
相关文章:
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 将父类对象强制转换为子类的问题
- 将方法转换为调用该方法的成员函子对象会导致崩溃
- 已转换对象的地址
- 如何在OpenGL中使用关键事件来转换对象
- 使用父类实例化的向下转换对象
- 静态强制转换允许转换对象指针,但不允许转换整数
- 为什么类型转换对象不会更改其地址?有关对象类型的信息存储在哪里?
- 找到对象类型后,是否可以使用 static_cast 强制转换对象
- 旨在复制/转换对象的功能系列的模板
- luabind 如何隐式强制转换对象
- 转换对象
- 使用隐式可转换对象调用move重载函数时的编译错误
- 关于在 cpp 中转换对象的两个问题
- 在运行时根据实例变量强制转换对象(c++)
- 使用用户定义的类型强制转换对象
- 在c++中转换对象
- 从"int"到非标量类型赋值运算符的转换 - 对象到 int
- 在屏幕上转换对象可编程管道
- 在 C 样式类型转换期间,关于强制转换对象的地址空间的实际情况