【发布时间】: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