问题
look at following code:
class A
{
public:
virtual int getN() = 0;
};
class B : public A
{
private:
int n = 2;
public:
int getN() { return n; }
};
class C : public A
{
// do not contain property n, it nolonger need getN();
};
class A is a abstract class. Now I have class C derived from A. But it dose not like class B has a property n. So I can't overload getN(), and then class C is a abstract class, which I cannot instantiate it.
So if I want instantiate class C, what should I do?
回答1:
Inheritance represents a "kind-of" relationship.
Since C does not have a getN() method, it cannot be a "kind of" A since anyone holding a reference to an A has the right to expect getN() to be present.
They have this right because you asserted it by putting getN in the public virtual interface of A.
Moral of the story - avoid inheritance if you can. Prefer encapsulation.
回答2:
You can try to split A into separate interfaces, which allows sub classes to pick and choose which properties of A they wish to inherit.
Take this, for example:
class A
{
public:
virtual int getN() = 0;
};
class A1
{
public:
virtual int getNum() = 0;
};
class B : public A, public A1
{
private:
int n = 2;
public:
int getN() override { return n; }
int getNum() override { return 42; }
};
class C : public A1
{
public:
virtual int getNum() override { return 1; }
};
Here, C no longer needs getN() so it inherits only from the interfaces that it needs. This pattern is commonly referred to as the interface segregation principle.
来源:https://stackoverflow.com/questions/33847779/how-to-convert-abstract-class-to-normal-class-without-overload-pure-virtual-func