2012-04-01 179 views
2

我現在在工作中也有類似的設計問題。我有一個基類等是否可以將成員變量作爲參數傳遞給C++中的成員函數?

class base 
{ 
protected: 
    update() 
    { 
    // do some stuff with a and b, call it as action A 
    } 

    int a, b; 
}; 

class derived : public base 
{ 
protected: 
    update() 
    { 
    // want to do the same action A , but with varaiables c and d 
    } 

    int c, d; 
}; 

和要求,派生類既需要的操作,諸如在「A和B」和「c和d」 ASLO動作。因此,可以設計一個像update(int,int)這樣的方法,這樣我就可以在需要時傳遞參數「a和b」和「c和d」並對它們執行操作。並且我知道我可以編寫一個輔助方法來執行這個動作,但是這個動作是特定於這個類的,我不能將它與這個分開。我可以有其他更好的替代方案嗎?

實時它的一個更大的類和行動也不是整數,它的一些對象反過來,varibales應該與類有關。

+0

你的問題就沒有意義了。您定義的整數都不是成員變量。那些應該被定義在'update'方法之外? – 2012-04-01 08:12:21

+0

是的,a和b是基類成員。 c和d是派生類成員。我想要使​​用相同的方法在這兩個變量對上執行相同的操作 – Amaravathi 2012-04-01 08:17:24

回答

3

您可以從派生類實現中調用基類實現。只需撥打base::update()即可。例如,看here

+0

問題是不同的...... – 2012-04-01 07:25:55

+1

問題不是很清楚 – littleadv 2012-04-01 18:45:49

1

我會重新審視你的class derived是否有is-a關係(爲您展示)或has-a關係,是這樣的:

class contains 
{ 
protected: 
    base x, y; 
    update() { x.update(); y.update(); } 
}; 
+0

是一種關係。 – Amaravathi 2012-04-01 08:11:04

1

你問什麼是技術上是可行的,只是定義

void update(int& a, int &b) 

update內部遺忘了關於類的memebrs,並且總是參考該參數並將其稱爲 update(a,b)update(c,d)

這裏的要點是要了解update是否真的是一個成員函數(它還需要訪問其他成員變量),或者只是一個靜態成員(它留在類空間中,但不會看到類成員本身),如果類之間的關係是正確的(那隻意味着嵌入vs繼承)。但是,這些方面應該基於考慮的不僅僅是一個單一的呼叫相關的那些其他......

2

是的,這是完全合法的:

class base 
{ 
protected: 
    void update() 
//^^^^ You forgot the return type. 
    { 
     doUpdate(a, b); 
    } 
    void doUpdate(int& x, int& y) 
    { 
    // do some stuff with x and y 
    // Because x and y are passed by reference they affect the original values. 
    } 
private: // Should probaly make the member vars private 
    int a, b; 
}; 

class derived : public base 
{ 
protected: 
    void update() 
//^^^^ You forgot the return type. 
    { 
    doUpdate(c, d); 
    } 
private: // Should probaly make the member vars private  
    int c, d; 
}; 
+0

謝謝你的回答。我對你的回答再次擔憂的是爲什麼我們需要更新和更新,有兩種方法。我們可以只有doUpdate,可以服務我們的目的。 – Amaravathi 2012-04-01 16:08:18

+0

@Amaravathi:是的,你可以使用'update()'而不是'doUpdate()',因爲第二個版本具有不同的簽名(兩個參數在第二個版本中傳遞)。但個人(爲了清晰起見)我會用兩個不同的名字。 – 2012-04-01 18:44:29

相關問題