最近我不得不在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
'int * asdf = new int();' - 您正在創建一個影響數據成員的局部變量。您可以通過正確的選項獲得警告。 – chris
引用在哪裏?我看到的只是指針。 – cdhowie
除了邏輯錯誤,它在GCC 4.7.2中編譯得很好:http://liveworkspace.org/code/e11908eab4281b5c1e73b980a0743ca6 – chris