本文介绍了作为类成员初始化的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我想通过将这样的引用作为参数传递给构造函数来初始化一个类的属性,该类保存对另一个类的引用.但是我收到一个错误:
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
推荐答案
您正在尝试分配给 bank
,而不是对其进行初始化:
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
是一个引用,因此必须对其进行初始化.你可以把它放在初始化列表中:
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)
{}
这篇关于作为类成员初始化的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!