发贴娱乐一下
在Java版偶然看到这样的题,挺好玩的,拿出来大家做一做,就当成散散心~
1.
有A,B两个类,其中A类有方法m1、m2、m3、m7、m9,B类有方法m1、m2、m3、m4、m5。
注:A类的m1,m2,m3和B类的方法同名,同功能。
问题:现在将会有一个C类要使用到m1,m2,m3和A类的m7及B类的m4方法,请写出你的想法或怎么操作(或者说在A与B功能不变时优化一下类结构)?
2.
顺便也聊一下
2.1在项目中如何使用抽象类与接口的
2.2什么情况下使用哪种设计模式比较干练...
[解决办法]
#include <iostream>using namespace std;class A {public: void M1(){std::cout<<"M1"<<endl;} void M2(){std::cout<<"M2"<<endl;} void M3(){std::cout<<"M3"<<endl;} void M7(){std::cout<<"m7"<<endl;}protected:private:};class B{public: void M1(){std::cout<<"M1"<<endl;} void M2(){std::cout<<"M2"<<endl;} void M3(){std::cout<<"M3"<<endl;} void M4(){std::cout<<"m4"<<endl;}protected:private:};class AB: public A, public B{public:protected:private:};int main(){ AB *test = new AB; test->A::M1(); test->B::M1(); test->M4(); delete test; return 0;}
[解决办法]
C類應該是一個組合類,采用委托實現接口
IMethod = Interface procedure m1; procedure m2; procedure m3;end;IA = Interface procedure m4; procedure m5;end;IB = Interface procedure m7; procedure m9;end; TExample=class(TInterfacedObject,IExample) private //子类共用的数据成员 public procedure M1;virtual; procedure M2;virtual; procedure M3;virtual; procedure other;virtual;abstract; end; TExampleA(TExample,IA) public procedure M4; procedure M5; end; TExampleB(TExample,IB) public procedure M7; procedure M9; end; TExampleC(TExample,IA,IB) private FA: IA; FB: IB; public constructor Create; property ExampleA: IA read FA implements IA; property ExampleB: IB read FB implements IB; end;implement ....constructor TExampleC.Create; begin FA:= TExampleA.Create; FB:= TExampleB.Create;end;
[解决办法]
写个玩玩,不过可能不是很合题意
type TCustomFuncArgs = class(TObject); TM1FuncArgs = class(TCustomFuncArgs); TM2FuncArgs = class(TCustomFuncArgs); TM3FuncArgs = class(TCustomFuncArgs); TM1FuncArgs = class(TCustomFuncArgs); TM4FuncArgs = class(TCustomFuncArgs); TM5FuncArgs = class(TCustomFuncArgs); TM7FuncArgs = class(TCustomFuncArgs); TM9FuncArgs = class(TCustomFuncArgs);
[解决办法]