2

我在设计这样的课程时遇到了麻烦

class C1 {
public:
  void foo();
}

class C2 {
public:
  void foo();
}

C1 和 C2 具有相同的方法 foo(),

class Derived1 : public Base {
public:
  void Update() {
    member.foo();
  }
private:    
  C1 member;
}

class Derived2 : public Base {
public:
  void Update() {
    member.foo(); 
  }
private:    
  C2 member;
}

两个 Derived 类的 Update() 完全相同,但成员的类型不同。所以我必须为每个新的派生类复制更新实现。

这是减少这种代码重复的一种方法吗?我只提出了一个带有宏的解决方案。我认为有一种更优雅的方法可以用模板解决这个问题,但我想不通..

编辑: 非常感谢大家,但我想我错过了一些东西..

1.我用的是c++

2.实际上每个 Derived 类有大约 5 个成员,它们都提供 foo() 方法并且派生自同一个基类。我的情况是我已经编写了一个(很长的)Update() 方法,它可以在每个派生类中工作而无需任何修改。所以我只是将这个 Update() 复制并粘贴到每个新类的 Update() 中,这会导致可怕的代码重复。我想知道是否有一种方法不需要我过多地重写 Update() 并且可以减少重复。

再次感谢

4

4 回答 4

6

这正是类模板所设计的那种应用程序。它们允许类中的函数对不同的数据类型进行操作,而无需复制算法和逻辑。

这个 Wikipedia 页面将为您提供编程中模板的一个很好的概述。

以下是帮助您入门的基本思路:

template  <class T>
class CTemplateBase
{
public:
    void Update()
    {
        member.foo();
    }
private:
    T member; // Generic type
}

class CDerived1 : public CTemplateBase<C1>
{
    // No common algorithms required here
}

class CDerived2 : public CTemplateBase<C2>
{
    // No common algorithms required here
}
于 2009-05-08T05:27:56.333 回答
0

如果您可以控制 C1 和 C2,则可以定义一个基类或抽象基类,并在基类或第三个辅助类中处理它。

于 2009-05-08T05:27:34.167 回答
0

将方法移动到父类:

class IFooable {
public:
  virtual void foo() = 0;
}

class C1 : IFooable {
public:
  void foo();
}

class C2 : IFooable {
public:
  void foo();
}

class Base {
public:
  void Update() {
    member->foo(); 
  }
private:    
  IFooable* member
}

class Derived1 : public Base {
  Derived1 () : member(new C1()) {}
  ~Derived1 () { delete member; }
}

class Derived2 : public Base {
  Derived2 () : member(new C2()) {}
  ~Derived2 () { delete member; }
}
于 2009-05-08T05:29:11.573 回答
0

如果您的 Drived1 和 Derived2 除了成员的类型(C1 和 C2)是相同的,那么您可以考虑使用单个类 Derived 和一个模板。(如果我的语法不正确,请原谅我的语法,我是 C# dev :D)

template <class T>
class Derived : public Base {
public:
  void Update() {
    member.foo();
  }
private:    
  T member;
}

上面几行的东西。

于 2009-05-08T05:34:18.097 回答