【问题标题】:multipile inheritance logic in C++C++中的多重继承逻辑
【发布时间】:2016-06-12 08:45:52
【问题描述】:

假设我有一个函数 f=sigma(phi(x)),我想为函数 sigma 和 phi 分配不同的形式。假设我们有两个 sigma 函数和两个 phi 函数,所以我们有 4=2* 2种组合。我怎样才能做到这一点?

如果只对f=sigma(x),我把sigma写成f中的虚函数,把sigma的具体形式定义为子类。

class sigma1: public class f{sigma=sigma1}

class sigma2: public class f{sigma=sigma2}

但是当涉及到 phi 时,我真的很困惑。我想我再次需要将 phi 定义为虚函数。但是对于一个特定的 phi,它应该是

class phi1 : public sigma1, public sigma 2

class phi2 : public sigma1, public sigma 2

假设我想创建一个对象 sigma1+phi1。我怎么能这样做?如果我简单地写

phi1 object1

那么显然它将无法知道使用 sigma1 或 sigma2。虚拟继承似乎也不起作用。我知道我可以像

这样创建四个类
class phi1 : public sigma1 {phi=phi1}

class phi2 : public sigma2 {phi=phi1}

class phi3 : public sigma1 {phi=phi2}

class phi4 : public sigma2 {phi=phi2}

但这似乎并不聪明....

【问题讨论】:

标签: c++ inheritance


【解决方案1】:

不清楚,对我来说,你打算如何使用你的类(或函数,或者你想要什么),但我建议你以下简单的解决方案,它基于你的 phi() 和sigma() 函数是接收 T 类型的变量并返回相同类型的值 T 的函数。

所以我构建了一个模板仿函数,它接收类型 T 和函数 SigmaPhi 作为参数

template <typename T, T (*Sigma)(const T &), T (*Phi)(const T &)>
struct f
 {
   T operator() (const int & x) const
    { return Sigma(Phi(x)); }
 };

以下是 sigma() 和 phi() 函数接收int 并返回int 的完整示例

#include <iostream>

int sigma1 (const int & x)
 { return x+1; }

int sigma2 (const int & x)
 { return x-1; }

int phi1 (const int & x)
 { return x+10; }

int phi2 (const int & x)
 { return x-10; }


template <typename T, T (*Sigma)(const T &), T (*Phi)(const T &)>
struct f
 {
   T operator() (const int &x) const
    { return Sigma(Phi(x)); }
 };


int main ()
 { 
   f<int, sigma1, phi1>  f11;
   f<int, sigma1, phi2>  f12;
   f<int, sigma2, phi1>  f21;
   f<int, sigma2, phi2>  f22;

   std::cout << "f11(100) = " << f11(100) << std::endl;
   std::cout << "f12(100) = " << f12(100) << std::endl;
   std::cout << "f21(100) = " << f21(100) << std::endl;
   std::cout << "f22(100) = " << f22(100) << std::endl;

   return 0;
 }

其他解决方案是可能的;例如,您可以编写模板函数而不是模板仿函数。

但是,我再说一遍:不清楚,对我来说,你想获得什么。

p.s.:对不起我的英语不好

【讨论】:

    猜你喜欢
    • 2011-03-29
    • 2017-03-31
    • 2012-05-14
    • 2013-08-28
    • 2011-01-16
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多