我目前正在学习 C++,但它并没有像我预期的那样工作。我为 BowlingGame 制作了一些类(class)(只是一些基于文本的类(class))并且效果很好。但现在我想将 BowlingGame 的对象传递给另一个类,称为 ScoreCalculator。
头文件如下所示:
#ifndef SCORECALCULATOR_H
#define SCORECALCULATOR_H
#include "BowlingGame.h"
class ScoreCalculator {
private:
BowlingGame * game;
public:
//constructor
ScoreCalculator(const BowlingGame &game);
//setters
void setGame(const BowlingGame &game);
};
#endif // SCORECALCULATOR_H
实现看起来是这样的:
#include "ScoreCalculator.h"
#include "BowlingGame.h"
#include <iostream>
using namespace std;
ScoreCalculator::ScoreCalculator(const BowlingGame &game) {
setGame(game);
}
void ScoreCalculator::setGame(const BowlingGame &gamse) {
//* game = gamse; this fails
//cout << gamse.getLastFrameNummer(); this works
}
我想在实例变量游戏中保存“BowlingGame 对象”,但由于某种原因我的控制台应用程序崩溃了。我不知道我做错了什么。失败在规则中:
* game = gamse;
我在互联网上查找了一些示例,但找不到解决方案。
最佳答案
这里的问题是您没有分配指针。为什么不在标题中将“游戏”定义为 BowlingGame 游戏;
?这样您的其他代码就可以正常工作。这意味着 BowlingGame 结构被“复制”到类(class)中的结构中,但这听起来正是您所追求的。
关于C++传递一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16375384/