我想在類似於下面的例子的情況下得到一些設計類的建議。 B和C對象可能有也可能沒有數字組件。問題是沒有辦法有選擇地調用一個NumberComponent構造函數。有沒有更好的方法來設計這個?上課設計的困境
class NumberComponent
{
public:
//Objects which don't have a number component just store a null pointer.
//Any time we do anything here, we have to make sure p_int isn't null.
NumberComponent() : p_int(0) { }
NumberComponent(int x) { p_int = new int(x); }
~NumberComponent() { delete p_int; }
void DoSomething() { if(p_int) ++(*p_int); }
//In real situation, this will be another complex class object.
//Using an int* here to keep this class simple for example.
int* p_int;
};
//B objects may or may not have a number component.
class B : public NumberComponent
{
public:
//If hasNumberComponent is false, we'd like to call the default constructor.
//If hasNumberComponent is true, we'd like to call NumberComponent(int) constructor.
B(int x, bool hasNumberComponent) {}
int value;
};
//C objects may or may not have a number component.
class C : public NumberComponent
{
public:
//If hasNumberComponent is false, we'd like to call the default constructor.
//If hasNumberComponent is true, we'd like to call NumberComponent(int) constructor.
C(int x, bool hasNumberComponent) {}
int value;
};
int main()
{
//myList contains NumberComponent* to B and C objects
std::list<NumberComponent*> myList;
myList.push_back(new B(5, true));
myList.push_back(new C(3, true));
for(std::list<NumberComponent*>::iterator i = myList.begin(); i != myList.end(); ++i)
(*i)->DoSomething();
//These objects don't have a Number component.
B b(2, false);
C c(1, false);
return 0;
}
如果'B'和'C'是從'NumberComponent'派生的,那麼它們**是**'NumberComponent's。所以說他們「可能有或沒有數字組件」是毫無意義的。 – 2012-03-03 22:10:05
順便說一句:不要使用動態分配的對象(即通過'new'),除非必須。我看不出有什麼理由在你的示例代碼中使用'new'! – 2012-03-03 22:10:50
我覺得我對於如何思考這個有點困惑。我想讓一些B和C對象有一個p_int並能夠做DoSomething()之類的事情。其他B和C對象將是相同的,除了它們不需要p_int並且不應該能夠執行諸如DoSomething()之類的操作。 – user987280 2012-03-03 22:17:59