如何描述继承class?
How to describe the inherited class?
我有一个 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};
在这种情况下使用模板怎么样:
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);
}
我有一个 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};
在这种情况下使用模板怎么样:
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);
}