2016-03-28 24 views
3

我有以下簡單的類轉換:轉換操作INT()失敗的static_cast和reinterpret_cast的

#include <iostream> 
using namespace std; 

template<int p> 
class Mod { 
    int n; 

    friend Mod operator+(const Mod &x, const Mod &y) { 
     const int sum = x.n + y.n; 

     if (sum < p) { 
      Mod z(sum); 
      return z; 
     } else if (sum >= p) { 
      Mod z2(sum - p); 
      return z2; 
     } 
    } 

    operator int() { 
     if (p == 0) return n; 
     if (p == 1) return 0; 

     for (int r = 0; r <= abs(n); r++) { 
      if (((r - n) % p) == 0) { 
       return r; 
      } 
     } 
    } 

    friend Mod operator-(const Mod &x) { 
     if (x.n == 0) return 0; 

     Mod z(-static_cast<int>(x) + p); 
     return z; 
    } 

    friend std::ostream &operator<<(std::ostream &out, const Mod &x) { 
     out << reinterpret_cast<int>(x); // invalid cast from type ‘const Mod<5>’ to type ‘int’ out << reinterpret_cast<int>(x); 
     return out; 
    } 

public: 
    Mod(int x) { 
     n = x; 
    } 
}; 

int main() { 
    Mod<5> z(3), x(2); 

    cout << z + x << endl; // error: invalid cast from type ‘const Mod<5>’ to type ‘int’ out << reinterpret_cast<int>(x); 
    cout << z << endl; //error: invalid cast from type ‘const Mod<5>’ to type ‘int’ out << reinterpret_cast<int>(x); // invalid cast from type ‘const Mod<5>’ to type ‘int’ out << reinterpret_cast<int>(x); 
    cout << -x << endl; //error: invalid static_cast from type ‘const Mod<5>’ to type ‘int’ Mod z(-static_cast<int>(x) + p); 

    return 0; 
} 

當我嘗試編譯並運行他們,我看到以下消息:

[ 33%] Building CXX object CMakeFiles/TestCpp.dir/main.cpp.o 
/home/user/ClionProjects/TestCpp/main.cpp: In instantiation of ‘std::ostream& operator<<(std::ostream&, const Mod<5>&)’: 
/home/user/ClionProjects/TestCpp/main.cpp:75:17: required from here 
/home/user/ClionProjects/TestCpp/main.cpp:56:13: error: invalid cast from type ‘const Mod<5>’ to type ‘int’ 
out << reinterpret_cast<int>(x); // invalid cast from type ‘const Mod<5>’ to type ‘int’ out << reinterpret_cast<int>(x); 
^ 
/home/user/ClionProjects/TestCpp/main.cpp: In instantiation of ‘Mod<5> operator-(const Mod<5>&)’: 
/home/user/ClionProjects/TestCpp/main.cpp:77:14: required from here 
/home/user/ClionProjects/TestCpp/main.cpp:50:36: error: invalid static_cast from type ‘const Mod<5>’ to type ‘int’ 
Mod z(-static_cast<int>(x) + p); 

回答

4

對於static_cast

使用隱式轉換和用戶定義轉換的組合轉換類型。

用戶定義的轉換將被考慮,但你鑄造intconst對象,你應該讓operator int() const成員函數:

operator int() const { 
       ~~~~~ 
    ... 
} 

對於reinterpret_cast

將轉換通過重新解釋潛在的位模式,在類型之間。

static_cast不同,但與const_cast類似,reinterpret_cast表達式不會編譯爲任何CPU指令。它純粹是一個編譯器指令,指示編譯器將表達式的位序列(對象表示)視爲具有new_type類型。

因此reinterpret_cast<int>(x)將無法​​正常工作,並且不會考慮用戶定義的轉換。

相關問題