你能解释一下如何调用类的方法吗?
Can you explain how the methods of the class are called?
conv.h
class Base
{
public:
void foo();
};
class Derived: public Base
{
public:
void bar();
};
class A {};
class B
{
public:
void koko();
};
转换.cpp
void Base::foo()
{
cout<<"stamm";
}
void Derived::bar()
{
cout<<"bar shoudn't work"<<endl;
}
void B::koko()
{
cout<<"koko shoudn't work"<<endl;
}
主.cpp
#include "conv.h"
#include <iostream>
int main()
{
Base * a = new Base;
Derived * b = static_cast<Derived*>(a);
b->bar();
Derived * c = reinterpret_cast<Derived*>(a);
c->bar();
A* s1 = new A;
B* s2 = reinterpret_cast<B*>(s1);
s2->koko();
}
输出:
bar shoudn't work
bar shoudn't work
koko shoudn't work
为什么在运行时成功调用方法栏,尽管我创建了一个未派生的基类? 它甚至适用于两种类型的转换(静态和重新解释强制转换)。
与上述问题相同,但具有不相关的类(A和B)??
未定义的行为可以做任何事情,包括看起来有效。
它
正在工作(阅读:"编译而不是崩溃")因为你从不在名义上的"成员"函数中使用this
指针。 例如,如果你试图打印出一个成员变量,你会得到你期望的垃圾输出或崩溃 - 但这些函数现在不依赖于它们应该属于的类中的任何内容。 this
甚至可以NULL
他们所关心的一切。
编译器知道Derived
可以使用成员函数foo()
和bar()
,并且知道在哪里可以找到它们。 在你做完你的"技巧"之后,你有指向Derived
的指针.
事实上,它们是 Derived
类型的指针 - 无论与这些指针关联的数据是什么 - 允许它们调用与派生相关的函数foo()
和kook()
。
如前所述,如果您实际使用了指针中的数据(即读取或写入相对于属于 Derived 类this
的数据成员(在本例中您没有),那么您将访问不属于您的对象的内存。
相关文章:
- 在c++中多次调用方法
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 接收字符串并使用它来调用方法C++
- 使用 gmock c++ 在真实对象上调用方法
- 不带预处理器的调用方法/文件的文件名/行号
- JNI从Android调用C++方法
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何使用接口指针调用方法,该指针是其具体类的一部分,而不是接口的一部分
- 从内部类中的方法从包含类调用方法
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么派生类的实例从基类调用方法?
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 通过模板函数对未知类型调用方法
- 从基于迭代器的for循环转换后,如何在map::find()中调用方法
- 创建一个C++DLL以从C#DLL调用方法
- 如何从qt中的类中调用方法
- 如何在不迭代的情况下对数组中的每个元素调用方法
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- C ++:如何在不创建对象的情况下在主函数中调用方法