2015-10-11 18 views
1

我有一個私人詮釋指數在這裏。私有詮釋值沒有改變類功能

class classname { 

    private: 
    int index; 
    public: 
    classname(); 
    void stuff(); 
} 

,並在我的構造我初始化index = 10;

classname::classname { 
    index = 10; 
} 

,但我想改變它在我stuff()功能,所以我在我的主文件,這樣做

classname::void stuff() { 
    cout << "the current index is: " << index << endl; 
    index = 15; 
    cout << "ending index is: " << index << endl; 
} 

我有

int main() { 
    classname name; 
    name.stuff(); 
    name.stuff(); //do it again 
} 

第二次再次返回到10,但它應該返回15。 這裏是結果:

the current index is: 10 
ending index is: 15 
the current index is: 10 
ending index is: 15 

請幫助

+2

如果你修復了你的語法錯誤,它可以在我的機器上運行。請發佈您編寫的實際(可運行)代碼。 – Dair

+0

所以我在函數的開頭使用cout進行了測試,並且在函數的結尾處,它確實給了我10個開頭和15個結束,第二次我調用它在開始時再次給出的函數10最後15個。 (對不起,我不能真正把整個代碼) –

+0

問題是,如果我修復您的代碼工作,然後在適當的地方調用cout,它會給我的電腦上的10,15,15。如果您無法提供完整的代碼,那麼我無法幫助您,因爲我無法重現您的問題。 – Dair

回答

0

試試這個修復:調用索引使用類名::指數

,因爲你使用範圍解析運算符(訪問私有成員::)

#include <iostream> 
using namespace std; 
class classname { 
private: 
int index; 
public: 
classname(); 

void stuff(); 
}; 
classname::classname() { 

classname::index = 10; 

cout<<classname::index<<endl; 
} 
void classname::stuff() { 

cout<<"Current: "<<index<<endl; 

classname::index = 15; 

cout<<"ending: "<<index<<endl; 
} 

int main() { 
classname name; 
name.stuff(); 
name.stuff(); //do it again 
return 0; 
} 
+0

nope添加類標頭不起作用。好主意,但我認爲這將工作 –

+0

它爲我工作。你能告訴我你的更新代碼嗎? – vishal

+0

我可以給你發私人密碼嗎? –

相關問題