【问题标题】:How to describe the inherited class?如何描述继承的类?
【发布时间】:2020-06-06 15:41:18
【问题描述】:

我有一个 Base 和 许多 (1..N) 类似的派生类:

class Base {
public:
  virtual void OnMouseMove(int x, int y) = 0;
}

class Derived_1: public Base {
public:
  void OnMouseMove(int x, int y) override;
}

class Derived_2: public Base {
public:
  void OnMouseMove(int x, int y) override;
}

void Derived_1::OnMouseMove(int x, int y) {actions 1};
void Derived_2::OnMouseMove(int x, int y) {actions 2};

所有派生类都有相同的定义,但不同 OnMouseMove() 函数。 我不喜欢程序的外观,因为我必须在头文件中写入所有相同的派生函数,只是名称不同的 Derived_1、Derived_2。

是否可以编写更短的程序?我需要这样的东西:

class Derived: public Base {
public:
  void OnMouseMove(int x, int y) override;
}

class Derived_1 : public Derived{};
class Derived_2 : public Derived{};

void Derived_1::OnMouseMove(int x, int y) {actions 1};
void Derived_2::OnMouseMove(int x, int y) {actions 1};

【问题讨论】:

  • 不,这是不可能的。这也为你每节课节省了 2 行,这真的值得吗?
  • 也许,你可以看看我的回答 (stackoverflow.com/a/60258003/3421515),这可能是有益的。
  • 不是很重要,只是有趣。派生类中有很多函数,如 OnMouseDown() 等。我只是喜欢代码看起来很漂亮。
  • 这可能是合法宏使用的情况。

标签: c++ templates derived-class base-class


【解决方案1】:

在这种情况下使用模板怎么样:

class Base {
public:
  virtual void OnMouseMove(int x, int y) = 0;
};  

template < int N>
class Derived: public Base {
public:
  void OnMouseMove(int x, int y) override;
};

template<> void Derived<1>::OnMouseMove(int x, int y) {std::cout<< "1"<< std::endl;}
template<> void Derived<2>::OnMouseMove(int x, int y) {std::cout<< "2"<< std::endl;}

int main()
{
    Base* ptr1 = new Derived<1>;
    Base* ptr2 = new Derived<2>;

    ptr1->OnMouseMove(5,6);
    ptr2->OnMouseMove(5,6);
} 

【讨论】:

  • @Peter-ReinstateMonica:如果你有编译器,你可以对其进行测试 :-) 我的编译器达到了我的预期......(gcc 9.2.1 & clang 9.0.0)。
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多