static_cast
- C/C++ code
http://www.cplusplus.com/doc/tutorial%20%20/typecasting/ class CBase {};class CDerived: public CBase {};CBase * a = new CBase;CDerived * b = static_cast<CDerived*>(a);This would be valid, although b would point to an incomplete object of the class and could lead to runtime errors if dereferenced.为什么运行会出错?? 如果 是因为继承类增加了 成员导致的 引用失败,那么 以下的例子 为什么又是对的??char * s="helloyxsgs";int* p=(int*)s; // p现在可以引用4个字节了, s只能引用一个。
- C/C++ code
问题2:关于static_cast 还有一段文字Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above. 是不是这样理解:假设有 类A,Bclass A{}; class B{ int data1; string str; }; int main() { A a; B b=static_cast<B>(a); //这里是错误的, 那段英文说是可以的啊。 }
[解决办法]
1.只是将字符串的前4个字节的内容当成Int来解释而已。
2.很明显你没看懂那段英文,这段文字说明的是被转换的原类的定义里面应该包含以目标类型为参数的构造函数或者是转型运算符的重载。
就你的例子来说 class A{ A(B obj); operator B();};必须包含里面两种的其中一种才可以static_cast
[解决办法]
不能把基类指针转化为派生类指针,可以用它来指向派生类的内容
[解决办法]
不能把基类指针转化为派生类指针