我怎样才能铸造为用户定义类型相同HANDELING内置的,如:C++:铸造为用户定义类型
float a = 5.4;
std::string s = a;//error, no conversion avaible
int x = a;//warning, possible data loss
int y = (int)a;//fine
int z = static_cast<int>a;//fine
float b = c;//warning, possible data loss
现在说,我有我自己的int和float类,怎么办我会得到相同的错误和警告?
class Int
{
public:
int value;
Int(int v);
...
};
class Float
{
public:
float value;
Float(float v);
...
};
Int c = 10;
Float a = 5.5;
std::string s = a;
Int x = a;
Int y = (Int)a;
Int z = static_cast<Int>a;
Float b = c;
我知道创造重载类型转换操作符,并使用构造的,但我不知道如何正确地做这项工作的隐式和显式转换,如考虑。如果我不在这些方法中添加明确的强制转换,那么在编译时会得到一个警告,但不会在调用时发出警告,如果我这样做,那么我不会在类代码中遇到错误,但我仍然没有得到警告什么时候使用。
我猜有一些方法,如果它试图隐式转换为标记转换运算符显式,从而生成一个警告,但不明确的(无论是C-风格或的static_cast)铸)
编辑: 好吧我想我得到这样的情况下,所有类型的问题是完全的,已知的,但什么时候一个或两个都是模板,并且这两种类型都映射到内置类型?
template<typename T> class Vector2
{
public:
T x, y;
Vector2():x(0),y(0){}
Vector2(T x, T y):x(x),y(y){}
//Works as expected, warning if adding T and T2 is unsafe, or error if
//incompatible*/
template<typename T2>Vector2<T>& operator += (const Vector2<T2> &v);
//Also works as desired
Vector2<T>& operator *= (T s);
//allows the conversion, but always generates warnings if
//T and T2 would, even if this constructor is used by an explicit
//case. How can I suppress the warnings for the explicit cast, but
//not for implicit casts?
template<typename T2>Vector2(const Vector2<T2> &v);//uses implicit conversion form T2 to T
};
比如从Vector2到Vector2隐式转换正常工作,但自投说Vector2到Vector2总是会引起(2,一个X和一个Y)警告,即使一个明确的C-风格或使用了static_cast。我想保留隐式转换的警告,但不要显式转换。
我知道我可以解决这个要创建一个特价T vector_cast(T2)键入使用显式转换为每个元素内部,但我宁愿能使用C风格和static_casts
static_cast <>通常是安全的,并且会给你你所期望的 - 无论如此,或者它将无法编译。 reinterpret_cast <>是危险的:它会编译,它会运行,你会得到一些根本没有意义的东西。 – 2009-10-06 22:05:24
是的,你是对的。我将编辑帖子。 – 2009-10-06 22:13:59
我加了c是:) – 2009-10-07 09:10:16