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' 必须在构造函数基类/成员初始化列表中初始化".以下类的代码有什么问题?
"'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)
{}
这篇关于作为类成员初始化的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:作为类成员初始化的引用


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01