引用作为类成员初始化 [英] Reference as class member initialization

查看:122
本文介绍了引用作为类成员初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将这样的引用作为参数传递给构造函数来初始化一个类的属性,该类拥有对另一个类的引用。但是我收到一个错误:

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'必须在构造函数库/成员初始化列表中初始化。
下面的类的代码有什么问题?

"'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


推荐答案

正尝试分配给银行,而不是将其初始化:

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

这篇关于引用作为类成员初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆