2012-10-31 34 views
1

最近我不得不在C++中使用C++作爲大學課程。我知道指針和引用的概念,但我在一個特定的點上謙卑。在C++中直接使用函數返回值作爲參考

考慮下面的類定義:

class test{ 
    public: 
     test(int i); 
     ~test(); 
     int* getint(); 
    private: 
     int *asdf; 
}; 

test::test(int i){ 
    asdf = new int(); 
    *asdf = i; 
} 

int* test::getint(){ 
    return asdf; 
} 

和下面的代碼:

void fun1(int*& i){ 
    *i +=1; 
} 

int main(){ 
    test *a = new test(1); 
    fun1(a->getint()); 
} 

,如果我連克編譯它++我會得到一個錯誤信息:

error: invalid initialization of non-const reference of type ‘int*&’ from an rvalue of type ‘int*’ 

我看到問題出在哪裏,可以通過聲明一個像這樣的新指針來解決:

int main(){ 
    test *a = new test(1); 
    int* b = a->getint(); 
    fun1(b); 
} 

但是有沒有其他方法直接使用返回值作爲參考? 如果我的C++代碼很糟糕,歡迎您糾正它(這基本上是我第一週的C++)。

編輯:改變FUN1使用的參考和修正類變量的動初始化(由enrico.bacis

+4

'int * asdf = new int();' - 您正在創建一個影響數據成員的局部變量。您可以通過正確的選項獲得警告。 – chris

+1

引用在哪裏?我看到的只是指針。 – cdhowie

+0

除了邏輯錯誤,它在GCC 4.7.2中編譯得很好:http://liveworkspace.org/code/e11908eab4281b5c1e73b980a0743ca6 – chris

回答

3

你定義在類測試陰影實例變量構造一個新的asdf變量的建議

更改行:

int* asdf = new int(); 

有:

asdf = new int(); 
1

有幾個問題,就像在C++中一樣,您必須正確管理內存,並且不能隨時調用新的內容,而不必在以後考慮刪除操作。

我覺得這

void fun1(int* i) 
{ 
    *i +=1; 
} 

會給+ = 1更高的運算符的優先級比*,所以你需要做的:

void fun1(int* i) 
{ 
    (*i) +=1; 
} 

注意函數需要採取int*作爲參數不是int *&。如果你想修改指針本身,而不是指向它,你只會採用int *&。在這種情況下,您無法傳入返回值爲getint(),這似乎是您的編譯器錯誤。

+0

感謝您的信息。在原始文件中有一個析構函數,它刪除指針。 – Moe