2011-10-09 159 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 ; 
}