gpt4 book ai didi

C++ - 基类指针、方法指针、引用派生类、方法?

转载 作者:太空宇宙 更新时间:2023-11-04 13:52:54 25 4
gpt4 key购买 nike

class Base
{
virtual void Foo(){}
virtual void Bar(){}
};

class Derived1 : public Base
{
void Foo(){ //Do something }
void Bar(){ //Do something }
}

class Derived2 : public Base
{
void Foo(){ //Do something }
void Bar(){ //Do something }
}

class OtherClass
{
public:
Base* obj;
void (Base::*method)();

void Add( Base* _obj, void (Base::*_method)() )
{
obj = _obj;
method = _method;
}

void Run()
{
( obj->method )();
}
}

int main()
{
Derived1 d1;
Derived2 d2;

OtherClass other;

other.Add( &d1, &(Derived1::Foo) );
//other.Add( &d2, &(Derived2::Bar) ); etc, etc.

other.Run();
}

我的问题:

假设我有一个带有方法的派生类,我可以使用该类的基类型指针来引用该类的实例。假设我知道我想调用什么方法,然后我可以通过该指针调用它,派生类的方法将被调用。

当我通过提供方法指针指定要调用的方法时,如何实现类似的多态行为?

如果我转换方法指针,上面所基于的真实代码将会编译,但它似乎没有做任何事情——在这一点上我意识到我没有调用 OtherClass 的更新方法,它是为什么我没有得到任何快乐。 :D 所以这(几乎)是有效的。愚蠢,愚蠢的大脑。

然后稍微修正一下:现在我需要将传递给 OtherClass 的方法指针静态转换为指向 Base 类方法的指针,当我将它传递给 Add 时。这并不理想。

例如,如果我将 &(Base::Foo) 传递给方法 Add,我能否获得相同的行为?

如果我在指向指向派生类型实例的基类型的指针上调用该方法,是否会调用 Derived1::Foo?

我感觉它会调用基本成员。 :(

一些阅读: Is it safe to "upcast" a method pointer and use it with base class pointer? C++ inheritance and member function pointers Pointer to member conversion Casting a pointer to a method of a derived class to a pointer to a method of a base class

最佳答案

我相信您正在考虑如果在派生类中提供,虚拟基的 member-fn-ptr 是否会触发多态派生覆盖。如果是这样,答案是肯定的,下面的代码证明了这一点。

希望这对您有所帮助。

#include <iostream>

class Base
{
public:
virtual void Foo()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
virtual void Bar()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};

class Derived1 : public Base
{
public:
void Foo()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}

void Bar()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};

class Derived2 : public Base
{
public:
void Foo()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}

void Bar()
{
std::cout << __PRETTY_FUNCTION__ << '\n';
}
};

class OtherClass
{
public:
Base* obj;
void (Base::*method)();

void Add( Base* _obj, void (Base::*_method)() )
{
obj = _obj;
method = _method;
}

void Run()
{
(obj->*method)();
}
};

int main()
{
Derived1 d1;
Derived2 d2;

OtherClass other;

other.Add( &d1, &Base::Foo );
other.Run();

other.Add( &d2, &Base::Bar);
other.Run();
}

输出

virtual void Derived1::Foo()
virtual void Derived2::Bar()

关于C++ - 基类指针、方法指针、引用派生类、方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22777942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com