c++ - 架构模式:处理两个相同实现的函数
问题描述
我有以下问题,鉴于我面临的问题,我想我解决的方法不正确:
我有一个接口I
和实现,A, B, C...
我想以某种方式表达我可以从夫妻(f(A,A),f(B,B),f(C,C))等等中得到一些结果。换句话说,我想接口 I 来表达两个相同的实现可以组合产生一些结果,而另一些则不能(你不能从 f(A, B) 得到任何有效的结果)。
现在我有以下内容:
#include <iostream>
using namespace std;
class A;
class B;
class I{
public:
virtual int f (const I &other) const = 0;
virtual int fSpecific (const A &other) const { throw runtime_error(""); };
virtual int fSpecific (const B &other) const { throw runtime_error(""); };
};
class A: public I{
public:
A(int a) : a(a) {}
int f (const I &other) const override { other.fSpecific(*this); }
int fSpecific (const A &other) const override { /*logic here*/ return a + other.a; }
int a;
};
class B: public I{
public:
B(int b1, int b2) : b1(b1), b2(b2) {}
int f (const I &other) const override { other.fSpecific(*this); }
int fSpecific (const B &other) const override { /*logic here*/ return b1*b1 + b2*b2 + other.b1*other.b1 + other.b2*other.b2; }
private:
int b1;
int b2;
};
int f(const I &a, const I &b) {
a.f(b);
}
int main()
{
cout << f(A(1), A(2)) << std::endl; // prints 3
cout << f(B(1, 2), B(3, 4)) << std::endl; // prints 30
cout << f(A(1), B(3, 4)) << std::endl; // throws an error
return 0;
}
/*and so on*/
但我想我使用了错误的架构。因为添加类会导致I
. 有没有更好的解决方案来表达这种关系?
解决方案
您可以雇用dynamic_cast
:
class I {
public:
template<typename T>
void fSpecific (T &other) {
if (dynamic_cast<T*>(this))
std::cout << "OK" << std::endl;
else
std::cout << "ERROR" << std::endl;
}
virtual ~I() {}
};
class A : public I {
};
class B : public I {
};
int main()
{
A a;
a.fSpecific(a);
B b;
b.fSpecific(a);
b.fSpecific((I&)a);
return 0;
}
不过也有一些问题:
- 多重继承
- 对象需要动态转换(这就是我添加虚拟接口的原因)
- 铸造
I
也有效。
推荐阅读
- ios - #selector(delete(_:)) 在 uitextfield swift 中崩溃
- c# - 使用 Newtonsoft.JSON 自定义转换器读取具有不同输入的 json
- postgresql - 将 postgresql 事务封装在一个结构中
- c++ - 我想以相反的顺序打印数组,我尝试编写与附图所示相同的代码,但我不明白为什么显示 0?
- kotlin - 使用 Kotlin Primary 构造函数时 val / var 的含义
- python - Django 无法打开 shape_predictor_68_face_landmarks.dat。RuntimeError:无法打开 shape_predictor_68_face_landmarks.dat
- android - 将应用程序内的区域设置自动更改为英语
- prolog - Prolog 中的组合子是什么?
- r - 什么是 For 循环?为什么在 R 中不需要它?
- vue.js - 如何在 VueRouter@4.0.0 (Vue3) 中使用 createAsyncComponent?