2011-10-09 161 views
1

我们可以投的对象与用户定义的类型,就像我们正常的数据类型吗? 好比说我们做类型转换为象int:铸造对象

INT variable_one =(int)的变量名;

所以我们可以做这样的:(复)OBJECT_NAME; 其中complex是使用operator + overloading为复数加法写的类。

是否有可能在这种正常的方式? 或者我们是否需要在调用此语句之前编写一些函数? 还是完全不可能像这样打字?

感谢很多:) 问候, 阿希什

回答

6

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)

article about type casting看一看或涉及任何C++入门书籍。

0

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

2

用户定义类型投定义转换运算符()的用户的类型。

前。)

#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 ; 
}