[英]How to let some derived classes use the same method, and some other derived classes use another?
考慮以下繼承層次結構:
class A{};
class X1:A{};
class X2:A{};
class Y1:X1{};
class Y2:X2{};
class Z1:X1{};
class Z2:X2{};
X層中可能還有更多的類,例如類X3:A {}; ...
每個X? 類有兩個派生類Y? 和Z?。
我需要添加一個所有Y1 ... Yn實例都執行相同的方法,並且所有Z1 ... Zn實例都使用另一種方法實現。
這是由類A中的方法調用的非公共方法。
有沒有完成此任務的優雅方法?
委托模式可能會回答您的問題
此示例是上面復雜Java示例的C ++版本。 由於C ++沒有接口構造,因此純虛類扮演相同的角色。 優點和缺點與Java示例大致相同。
#include <iostream>
using namespace std;
class I {
public:
virtual void f() = 0;
virtual void g() = 0;
virtual ~I() {}
};
class A : public I {
public:
void f() { cout << "A: doing f()" << endl; }
void g() { cout << "A: doing g()" << endl; }
~A() { cout << "A: cleaning up." << endl; }
};
class B : public I {
public:
void f() { cout << "B: doing f()" << endl; }
void g() { cout << "B: doing g()" << endl; }
~B() { cout << "B: cleaning up." << endl; }
};
class C : public I {
public:
// construction/destruction
C() : i( new A() ) { }
virtual ~C() { delete i; }
private:
// delegation
I* i;
public:
void f() { i->f(); }
void g() { i->g(); }
// normal attributes
void toA() { delete i; i = new A(); }
void toB() { delete i; i = new B(); }
};
int main() {
C c;
c.f(); //A: doing f()
c.g(); //A: doing g()
c.toB(); //A: cleaning up.
c.f(); //B: doing f()
c.g(); //B: doing g()
}
如果可以接受公共繼承,則可以定義父類,並在派生類中具有指向這些類的指針:
#include <iostream>
using namespace std;
class A
{
// A cannot be abstract - it must be able to invoke a
// "non-public method" whose implementation varies based on Y vs Z
public:
virtual void myFun()=0;
void callMyFun(){myFun();}
};
class Y
{
public:
void myFun(){cout<< "myFun from Y superclass" << endl;}
};
class Z
{
public:
void myFun(){cout<< "myFun from Z superclass" << endl;}
};
class X1:public A{};
class X2:public A{};
class Y1:X1{
Y* y;
void myFun(){y->myFun();}
};
class Y2:public X2{
Y* y;
void myFun(){y->myFun();}
};
class Z1:public X1{
Z* z;
void myFun(){z->myFun();}
};
class Z2:public X2{
Z* z;
void myFun(){z->myFun();}
};
int main()
{
Y2 myY2;
myY2.callMyFun(); // myFun from Y superclass
}
您可能想看看PIMPL慣用語。 函數實現封裝在您的Y *和Z *委托的類中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.