2013-04-29 15 views
0

對不起,有新手問題,但我想引用一個類/結構類型的組件作爲函數中的參數傳遞。我不知道是否使用如何在C++中引用結構組件

blah.memberFunction(&blah.component) 

blah.memberFunction((&blah).component) 
+0

你想傳遞一個指針或引用? – Pubby 2013-04-29 21:26:41

+0

如果您使用的是C++ 11,請考慮使用lambda:[](T blah){return blah.component; } – 2013-04-29 21:27:59

+0

@Pubby參考 – gr33kbo1 2013-04-29 21:33:46

回答

1

假設你的成員函數如下:

blah::memberFunction(blahType& component) 

調用它是這樣的:

blah.memberFunction(blah.component) 

使用& ope rator給你一個指針,與參考不同。參考文獻不需要操作員。

0

你是否參考類組件data members?在你所說的具體情況中:在大多數情況下,使用成員作爲參數調用方法是無用的。考慮代碼:

class blah 
{ 
public: 
    blah() : component(0) {} 
    void memberFunction() { component ++; } 
    int component; 
} 

int main() 
{ 
    blah b; 
    std::cout << b.component; //output = 0 
    b.memberFunction(); 
    std::cout << b.component; //output =1 
} 

請注意,在一個類的方法我已經有訪問數據成員:我爲什麼要使用它作爲它自己的方法的參數,並沒有聽起來有點沒用?

無論如何,如果你真的有一個很好的理由來實現它使用一個成員的引用,不僅僅是申報方法receive arguments by reference

class blah 
{ 
public: 
    blah() : component(0) {} 
    void callMemberFunction() 
    { 
     memberFunction(component); 
    } 
    void memberFunction(int &member_reference) { member_reference++; } 

    int component; 
} 

int main() 
{ 
    blah b; 
    std::cout << b.component <<"\n"; //output = 0 
    b.callMemberFunction(); 
    std::cout << b.component <<"\n"; //output =1 
}