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

ash*_*khe 3 c++ casting user-defined-types

我们可以使用用户定义的类型转换对象,就像我们对普通数据类型一样吗?比如说我们为int类型转换为:

int variable_one =(int)variable_name;

所以我们可以这样做:(复杂)object_name; 复杂是我为使用operator +重载添加复数而编写的类.

有可能以这种正常方式吗?或者在调用此声明之前我们是否需要编写一些函数?或者根本不可能像这样输入?

非常感谢:)问候,Ashish

Gre*_*osz 8

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++入门书.


BLU*_*IXY 6

用户定义的类型强制转换为用户类型定义的强制转换 operator()。

前任。)

#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 ;
}
Run Code Online (Sandbox Code Playgroud)