Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c++ - Reference as class member initialization

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:

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

#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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
{}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...