Reference as class member initialization

后端 未结 4 1304
野的像风
野的像风 2020-12-05 10:28

I want to initialize a property of a class that holds a reference to another class by passing such a reference as a parameter to the constructor. However I receive an error:

4条回答
  •  余生分开走
    2020-12-05 11:15

    You are attempting to assign to bank, not initialize it:

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

    bank is a reference, and therefore it must be initialized. You do so by putting it in the initializer list:

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

提交回复
热议问题