簡體   English   中英

以下代碼有什么錯誤?

[英]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)

如果這樣做,至少會發現兩個問題:

  • 參考資料應初始化;
  • 您不能將浮點指針分配給int指針。

(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;

是不正確的,因為pint*類型, &xfloat*類型。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM