2011-12-20 74 views
0

我的問題是關於在C數據類型轉換++。 C++是否爲內置數據類型(int,float)向用戶定義的數據類型提供隱式轉換?內置數據類型轉換到用戶定義的數據類型C++

在以下示例中,我試圖添加與測試對象類型雙(T4 = T3 + 1.0)和它的細使用+運算工作,所以是雙隱式轉換爲測試對象類型?

class test { 
double d; 
int m; 
public: 
test() 
{ 
    d=0; 
    m=0; 
} 
test(double n) 
{ 
    d=n; 
} 
const test operator+(const test& t) 
{ 
    test temp; 
    temp.d = d+ t.d; 
    return temp; 
} 
}; 

int main() 
{ 
    test t1(1.2); 
    test t2(2.5); 
    test t3, t4; 
    t3= t1+ t2; 
    t4 = t3 + 1.0; 
    return 0; 
} 
+4

此代碼[不能編譯](HTTP:// ideone。 com/gdhVO),因爲你的類'test'沒有任何構造函數,但你可以在'test t1(1.2)'中調用它。請發佈真實的代碼。 –

回答

0

構造test(double n)聲明從doubletest的隱式轉換。通常,任何構造,其與只有一個參數調用(包括可以採取更多的參數,但對這些默認值構造函數),可以被用作一個隱式轉換,除非它被標記explicit

struct Foo { 
    Foo(int x); // implicit conversion from int to Foo 
    explicit Foo(char c); // marked explicit - no implicit conversion 
    Foo(std::string a, double pi = 3.14159); // can be used as implicit 
              // conversion due to default 
              // argument 
}; 

編輯:t4 = 1.0 + t3不起作用,因爲你已經超負荷您operator+作爲一個成員函數,因此只考慮如果第一個操作數的類型是test的 - 隱式轉換不會在這種情況下嘗試。爲了使這項工作,讓您的運營商免費功能:

test operator+(const test& lhs, const test& rhs); 
+0

好..但是爲什麼t4 = 1.0 + t3不起作用?不應該像下面這樣隱式轉換:t4 = test(1.0)+ t3; – Ruchi

+0

編輯我的答案來解釋這一點。 –

+0

明白了..謝謝:) – Ruchi

0

是的,只要你的構造test(double)不明確

// implicite convertible 
test(double n) 
{ 
    d=n; 
} 

// not implicite convertible 
explicit test(double n) 
{ 
    d=n; 
}