c++中的C风格强制转换会产生奇怪的行为
C-Style casting in C++ giving weird behavior
我总是读到c++中的C风格强制转换与reinterpret_cast相同。然而,我刚刚在Visual Studio中测试了这段代码,似乎c风格的强制转换与静态强制转换执行相同的行为。有人知道为什么吗?这似乎是一个bug…
#include <string>
#include <iostream>
class Thing1
{
std::string theString;
public:
Thing1(const std::string& theString) : theString(theString)
{
//
}
std::string getTheString()
{
return theString;
}
};
class Thing2
{
std::string theString;
public:
Thing2(const std::string& theString) : theString(theString)
{
//
}
std::string getTheString()
{
return theString;
}
};
class Thing3 : public Thing1, public Thing2
{
public:
Thing3(const std::string& theString1, const std::string& theString2) : Thing1(theString1), Thing2(theString2)
{
//
}
};
int main()
{
Thing3* thing3 = new Thing3("string1", "string2");
uintptr_t t3ptr = (uintptr_t)thing3;
uintptr_t t1ptr = (uintptr_t)((Thing1*)thing3);
uintptr_t t2ptr = (uintptr_t)((Thing2*)thing3);
std::cout << t1ptr << std::endl;
std::cout << t2ptr << std::endl;
std::cout << t3ptr << std::endl;
std::cin.ignore();
return 0;
}
下面的代码给出了输出:
17563752
17563780
17563752
c风格的强制转换与reinterpret_cast不同。
剧组的总结可以在这里找到:http://en.cppreference.com/w/cpp/language/explicit_cast
,顺序如下:
) const_cast(表达式);
b) static_cast(expression),带有扩展:派生类的指针或引用也可以被强制转换为无二义性基类的指针或引用(反之亦然),即使基类不可访问(也就是说,这种强制转换忽略私有继承说明符)。同样适用于将成员指针转换为明确的非虚基的成员指针;
c) static_cast(带扩展)后面跟着const_cast;
d) reinterpret_cast(表达式);
e) reinterpret_cast接const_cast.
相关文章:
- 通过从当地的C风格阵列中返回指针来获取一个悬空的指针
- 将STD :: U8String复制到一个UTF8字符的C风格字符串中
- 这种尝试是在C 可靠 /安全的更为Python风格的装饰器中的尝试
- C 17中的Python风格装饰器
- SDL2 中的 GLFW 风格的无限鼠标移动
- 尝试使用std::functional和std::bind在C++中创建C#风格的事件访问修饰符
- 在C++代码中使用C风格的注释是不是一种糟糕的做法
- 以numpy/Python的风格访问OpenCV和C++中的矩阵元素
- 在班级中使用动态分配的C风格字符串,并带有复制和分配操作员,给出了意外的结果
- 我正在收到错误的“ list :: ShowList”:功能风格的初始化器似乎是我的CPP文件中的函数定义'
- C++OO风格中的引用计数
- 如何在C#中实现C++风格的函数指针?,不使用代理
- 在find()中提供布尔值是一种糟糕的风格吗
- C++宏中的函数式编程风格:这是否记录在任何地方
- 海湾合作委员会中的博兰德风格__closure
- 在代码中修改预处理器宏是一种好的风格吗
- C++11中的C风格回调
- c++中的C风格字符串和操作符重载
- c++中的C风格强制转换会产生奇怪的行为
- c++中的C风格初始化列表、结构和类构造函数