你能解释一下如何调用类的方法吗?

Can you explain how the methods of the class are called?

本文关键字:调用 方法 能解释 一下 何调用      更新时间:2023-10-16

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的数据成员(在本例中您没有),那么您将访问不属于您的对象的内存。