2013-09-21 38 views
0

這工作得很好:C++對象引用,而不是拷貝

udtCandidate firstCand; 
firstCand=uSeqs[i].Candidates.front(); 

這將創建udtCandidate的副本。

但我需要一個參考,而不是副本。

然而

udtCandidate firstCand; 
firstCand=&uSeqs[i].Candidates.front(); 

不起作用。 編譯器告訴我,沒有二元運算符「=」接受類型爲「udtCandidate *」的右手操作數。

有人知道我做錯了什麼嗎?

的聲明是:

struct udtCandidate 
{ 
    udtJoinFeatures JoinFeaturesLeft; 
    udtJoinFeatures JoinFeaturesRight; 
    udtByteFeatures ByteFeaturesLeft; 
    udtByteFeatures ByteFeaturesRight; 
    int iHPUnitIDLeft; 
    int iHPUnitIDRight; 
    double targetCost; 
    vector<unsigned long>bestPath; 
    double bestPathScore; 
    bool hasAncestor; 
}; 
struct udtCandidateSequence 
{ 
    double Score; 
    vector<udtCandidate>Candidates; 
}; 

回答

1

爲了存儲而不是值的引用,你必須創建一個引用變量:

udtCandidate& firstCand = uSeqs[i].Candidates.front(); 

使用&像你一樣意味着地址運算符,這又將類型更改爲指針。

+0

哦,好的。似乎我必須申報並將其分配在一行中。我試過聲明udtCandidate&firstCand;在一行中,並在下一行中進行賦值,但這不起作用... – tmighty

+0

這是因爲您不能有空引用。我建議你閱讀你的C++書中的主題。另外,一行中的初始化是一個很好的編程習慣。 –