gpt4 book ai didi

c++ - 从接口(interface)层次结构中获取接口(interface)

转载 作者:行者123 更新时间:2023-11-28 07:02:53 32 4
gpt4 key购买 nike

我有如下的接口(interface)层次结构:

class interface1
{
public:
virtual ~interface1() = 0;
}

class interface2 : public interface1
{
public:
virtual ~interface2() = 0;
}

我的数据模型具有可以从 Interface1 或 interface2 派生的类:

class cls1 : public interface1
{
}
class cls2 : public interface2
{
}

我想写一个在 interface1 或 interface2 上工作的重载函数

void function1(interface1 * obj)
{
// do something here
}
void function1(interface2 * obj)
{
// do something here
}

现在我想创建 cls1 和 cls2 的对象,并调用 function1:

{
.........
cls1 *p1 = new cls1;
cls2 *p2 = new cls2;

function1(p1);
function1(p2);
.........
}

我的问题是 - 在这两种情况下,总是调用 function1(interface1 * obj)。我不想将 if-else 与 dynamic_cast 结合使用(这是创建接口(interface)层次结构的全部意义)。谁能建议我使用 cls2 对象调用 function1(interface2* obj) 的方法?

最佳答案

您尝试做的事情听起来与虚函数非常相似。为什么不将 function1 定义为类的成员函数:

class interface1
{
public:
virtual void function1()
{
// Do what you want to do when deriving from interface1
}
}

class interface2 : public interface1
{
public:
virtual void function1()
{
// Do what you want to do when deriving from interface2
}
}

关于c++ - 从接口(interface)层次结构中获取接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22175686/

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