对于static_cast和reinterpret_cast,转换运算符int()失败

时间:2016-03-28 14:00:59

标签: c++ gcc type-conversion operators

我跟随转换的简单类:

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

1 个答案:

答案 0 :(得分:4)

对于static_cast

  

使用隐式转换和用户定义转换的组合在类型之间进行转换。

将考虑用户定义的转化,但是您要在int对象上转换为const,您应该使operator int() const成员函数:

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

对于reinterpret_cast

  

通过重新解释基础位模式在类型之间进行转换。

     

static_cast不同,但与const_cast类似,reinterpret_cast表达式不会编译为任何CPU指令。它纯粹是一个编译器指令,它指示编译器将表达式的位序列(对象表示)视为具有new_type类型。

所以reinterpret_cast<int>(x)无论如何都无法工作,用户定义的转化也不会被考虑。