2016-04-29 41 views
0

我可以重載'+'操作符,但我不知道如何爲NewType指定類型。我希望它被類型化爲任何其他變量類型。你能提供一些指點嗎?非常感謝!類型重載

#include <iostream> 

class NewType { 
private: 
    float val; 

public: 
    NewType(float v) { val = v; } 
    friend NewType operator+(const NewType &c1, const NewType &c2); 
    float GetVal() const { return val; } 
}; 

NewType operator+(const NewType &c1, const NewType &c2) { return NewType(c1.val + c2.val); } 

int main() { 
    NewType a = 13.7; 
    // Here is the problem, I would like this to print 13. 
    std::cout << (int) a << std::endl; 
    return 0; 
} 
+0

你需要爲你的類重載'operator int'。 – NathanOliver

+1

檢查例如[此用戶定義的轉換參考](http://en.cppreference.com/w/cpp/language/cast_operator)。 –

回答

2

I would like it to be typecasted to any other variable type.

對於任何其他變量類型你需要一個模板用戶定義的轉換:

class NewType { 
public 
// ... 
    template<typename T> 
    explicit operator T() const { return T(val); } 
// ... 
}; 

explicit(這裏是C++ 11及以上)可確保您將使用顯式強制,即:

NewType a = 13.7; 
int n = a; // compile error 
int n2 = static_cast<int>(a); // now OK 

你也可以使用統一的初始化在用戶定義的轉換操作符:

template<typename T> 
    explicit operator T() const { return T{val}; } 

這會給你額外的警告的情況下,你的施法可能需要縮小。但正如我在GCC看到默認情況下只產生警告(我記得這是由設計 - 由於大量的遺留代碼會破壞),下鐺它產生錯誤:

main.cpp:15:16: error: type 'float' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing] 
     return T{val}; 

和相同的Visual Studio生成錯誤。

+0

我不確定它是一個非常好的主意,可以在沒有約束的情況下對演員操作符進行模板化......這會使錯誤表達式中的其他簡單錯誤顯得虛假。它可以在你不會想到的地方做壞事...... – WhiZTiM

+0

@WhiZTiM我同意,這看起來很詭異 - 我已經添加了'explicit',因此必須使用外部投射 – marcinj