gpt4 book ai didi

c++ - 由于多个抽象基类,实现两个同名但不同的非协变返回类型的函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:27 24 4
gpt4 key购买 nike

如果我有两个抽象类定义一个具有相同名称但不同的非协变返回类型的纯虚函数,我如何从它们派生并为它们的两个函数定义一个实现?

#include <iostream>

class ITestA {
public:
virtual ~ITestA() {};
virtual float test() =0;
};

class ITestB {
public:
virtual ~ITestB() {};
virtual bool test() =0;
};

class C : public ITestA, public ITestB {
public:
/* Somehow implement ITestA::test and ITestB::test */
};


int main() {
ITestA *a = new C();
std::cout << a->test() << std::endl; // should print a float, like "3.14"
ITestB *b = dynamic_cast<ITestB *>(a);
if (b) {
std::cout << b->test() << std::endl; // should print "1" or "0"
}
delete(a);
return 0;
}

只要我不直接调用 C::test() 就没有任何歧义,所以我认为它应该以某种方式起作用,我想我只是还没有找到正确的表示法。或者这是不可能的,如果是的话:为什么?

最佳答案

好的,这是可能的,而且方法也不会太难看。我必须添加额外的继承级别:

 ITestA       ITestB     <-- These are the interfaces C has to fulfill, both with test()
| |
ITestA_X ITestB_X <-- These classes implement the interface by calling a
| | function with a different name, like ITestA_test
\__________/ which is in turn pure virtual again.
|
C <-- C implements the new interfaces

现在 C 没有函数 test(),但是当将 C* 转换为 ITestA* 时, 的实现ITestA_test 中的 test() 将被使用。当将其转换为 ITestB* 时,即使是来自 ITestA* 的 dynamic_cast,也会使用 ITestB_test 的实现。以下程序打印:3.140

#include <iostream>

class ITestA {
public:
virtual ~ITestA() {};
virtual float test() =0;
};

class ITestB {
public:
virtual ~ITestB() {};
virtual bool test() =0;
};

class ITestA_X : public ITestA {
protected:
virtual float ITestA_test() =0;
virtual float test() {
return ITestA_test();
}
};

class ITestB_X : public ITestB {
protected:
virtual bool ITestB_test() =0;
virtual bool test() {
return ITestB_test();
}
};

class C : public ITestA_X, public ITestB_X {
private:
virtual float ITestA_test() {
return 3.14;
}
virtual bool ITestB_test() {
return false;
}
};

int main() {
ITestA *a = new C();
std::cout << a->test() << std::endl;
ITestB *b = dynamic_cast<ITestB *>(a);
if (b) {
std::cout << b->test() << std::endl;
}
delete(a);
return 0;
}

你能想到这有什么缺点吗?

关于c++ - 由于多个抽象基类,实现两个同名但不同的非协变返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11371953/

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