2011-11-27 105 views
15

我想通過將這樣的引用作爲參數傳遞給構造函數來初始化保存對另一個類的引用的類的屬性。但是,我收到一個錯誤:引用作爲類成員初始化

「'TaxSquare :: bank'必須在構造函數庫/成員初始值設定項列表中初始化」。 下面的類代碼有什麼錯誤?

#ifndef TAXSQUARE_H 
#define TAXSQUARE_H 
#include "Square.h" 

class Bank; 

class TaxSquare : public Square 
{ 
    public: 
     TaxSquare(int, int, Bank&); 
     virtual void process(); 

    private: 
     int taxAmount; 
     Bank& bank; 

}; 
#endif 
#include <iostream> 
#include "TaxSquare.h" 
#include "Player.h" 
#include "Bank.h" 
using namespace std; 

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID) 
{ 
    taxAmount = amount; 
    bank = theBank; 
} 
#ifndef BANK_H 
#define BANK_H 

class Bank 
{ 
public: 
    Bank(int, int, int); 
    void getMoney(int); 
    void giveMoney(int); 
    void grantHouse(); 
    void grantHotel(); 

private: 
    int sumMoney; 
    int numOfHouses; 
    int numOfHotels; 

}; 

#endif 

回答

25

您正在嘗試將分配給bank,不初始化:

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID) 
{ 
    // These are assignments 
    taxAmount = amount; 
    bank = theBank; 
} 

bank是一個參考,因此它必須被初始化。您可以通過把它在初始化列表中這樣做:

TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) 
: Square(anID), taxAmount(amount), bank(theBank) 
{} 
4

的錯誤是你試圖通過一個未初始化的參考以分配:C++引用不能分配 - 這指的是,而不是分配對象 - 等,如果它是一個成員,它必須在初始化列表中進行初始化(就像編譯器所說的那樣)。

4

「'TaxSquare::bank' must be initialized in constructor base/member initializer list」. What is wrong in the following code of the classes?

什麼是錯的是,TaxSquare::bank沒有被初始化在構造函數基/成員初始化列表,正是因爲它說。

「構造函數庫/成員初始化列表」是相關構造函數TaxSquare::TaxSquare(int, int, Bank&)的初始化列表。您已經在使用它來初始化基地(Square)。您必須使用它來初始化bank成員,因爲它是引用類型。沒有在初始化列表中指定的事物會獲得默認初始化,並且沒有引用的默認初始化,因爲它們必須始終引用某些內容,並且沒有缺省值供他們引用。

老實說,我發現在C++中使用數據成員的引用比99年的時間值得的更麻煩。用智能指針,或者甚至是純粹的指針,你可能會更好。但你應該仍初始化與初始化列表,即使你可以離開沒有。真的,taxAmount也是如此。

// TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : Square(anID) 
// That thing after the colon is the initialization list:  ^^^^^^^^^^^^ 
// So add the other members to it, and then notice that there is nothing left 
// for the constructor body to do: 
TaxSquare::TaxSquare(int anID, int amount, Bank& theBank) : 
Square(anID), taxAmount(amount), bank(theBank) {} 
+0

+1對於「初始化列表中未指定的內容獲取默認初始化,並且沒有引用的默認初始化,因爲它們必須始終引用「 –

1

bank = theBank; 這一聲明意味着你要分配給OBJ1和OBJ2它會調用賦值運算符是錯誤的,因爲銀行的類型爲參考下面

TaxSquare :: TaxSquare提到必須intialized(INT ANID,詮釋金額,銀行& theBank ):Square(anID),bank(theBank){}