[英]What errors do following code have?
我仍然是C ++的初學者,應該在以下代碼中找到錯誤。
1 class Thing
2 {
3 public:
4 char c;
5 int *p;
6 float& f;
7 Thing(char ch, float x) { c = ch; p = &x; f = x; }
9 };
我知道在第六行有一個錯誤:引用f需要初始化。 但是我對第七行感到困惑。 它看起來像一個構造函數,但我不能確保p =&x;。 是正確的? 另外,如果我想更正引用初始化的錯誤,該怎么辦?
找出是否有錯誤的最佳方法就是簡單地對其進行編譯(1) 。
如果這樣做,至少會發現兩個問題:
(1)根據這份筆錄:
$ g++ -c -o prog.o prog.cpp
prog.cpp: In constructor ‘Thing::Thing(char, float)’:
prog.cpp:7:7: error: uninitialized reference member in ‘float&’ [-fpermissive]
Thing(char ch, float x) { c = ch; p = &x; f = x; }
^
prog.cpp:6:14: note: ‘float& Thing::f’ should be initialized
float& f;
^
prog.cpp:7:43: error: cannot convert ‘float*’ to ‘int*’ in assignment
Thing(char ch, float x) { c = ch; p = &x; f = x; }
^
p = &x;
是不正確的,因為p
是int*
類型, &x
是float*
類型。
f = x;
很可能不是您想要的。 您可能希望f
成為x
的引用。 上面的行不這樣做。 它將x
的值分配給f
引用的對象。
如果要讓f
成為x
的引用,則需要將其初始化為:
Thing(char ch, float& x) : f(x) { ... }
// ^^^ different from your signature
使用
Thing(char ch, float x) : f(x) { ... }
這是有問題的,因為一旦函數返回, f
將成為懸掛的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.