使用用户定义的类型强制转换对象

casting object with user defined type

本文关键字:转换 对象 类型 用户 定义      更新时间:2023-10-16

是否可以像处理普通数据类型那样使用用户定义类型强制转换对象?比如我们对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 ;
}

你为什么要这样做?我猜你应该写适当的构造函数,如果你想创建你的类的对象。如您所知,构造函数可以被重载。因此,如果需要以不同的方式构造对象,可以随意编写多个构造函数。