I am curious if there is a neat way to expose methods in the base class of a derived interface.
So in code: -
class cbase {
public:
void MyMethodA() { }
};
class cderived : public cbase {
public:
void MyMethodB() { }
}
class ibase {
public:
virtual void MyMethodA() = 0;
};
class iderived : public ibase {
public:
virtual void MyMethodB() = 0;
};
Now if I make cbase inherit ibase, and cderived implement iderived, the compiler will complain that when I instantiate cderived, MyMethodA() is abstract and not implemented.
MyMethodA() is implemented in the base class and through ibase. Is the only way to fix this to reimplement ibase's methods in the cderived class? If so, yuck!
So as below: -
class cbase : public ibase {
public:
void MyMethodA() { }
};
class cderived : public cbase, public iderived {
public:
void MyMethodA() { cbase::MyMethodA(); }
void MyMethodB() { }
};
cderived inst;
iderived *der = &inst;
der->MyMethodA(开发者_开发问答);
der->MyMethodB();
ibase *bas = der;
bas->MyMethodA();
I hope this is enough to convey the question. :) It might sound a little loopy as we are trying to refactor old code.
I am sure there is plenty of eager commentary out there ;)
If I understand correctly you want to make ibase
a virtual base class of iderived
and cbase
.
This was there is only one instance of each of your interface classes in the class hierarchy and when you join cbase
and iderived
together at the cderived
level the non-virtual override of MyMethodA
in cbase
is used because it is the dominating override.
See here: Hidden Features of C++?
E.g.
class ibase {
public:
virtual void MyMethodA() = 0;
};
class iderived : public virtual ibase {
public:
virtual void MyMethodB() = 0;
};
class cbase : public virtual ibase {
public:
void MyMethodA() { }
};
class cderived : public cbase, public virtual iderived {
public:
void MyMethodB() { }
};
int main()
{
cderived inst;
iderived *der = &inst;
der->MyMethodA();
der->MyMethodB();
ibase *bas = der;
bas->MyMethodA();
}
Take a look into multiple inheritance.
The answer to that faq item is basically answer to your question :
class cderived : public virtual cbase {
public:
void MyMethodB() { }
}
class ibase {
public:
virtual void MyMethodA() = 0;
};
class iderived : public virtual ibase {
public:
virtual void MyMethodB() = 0;
};
精彩评论