简体   繁体   English

C ++传递对象

[英]C++ passing an object

I'm currently learning C++, but It doesn't works like I expected. 我目前正在学习C ++,但无法正常运行。 I made some classes for a BowlingGame (just something text-based) and that works well. 我为BowlingGame制作了一些类(只是基于文本的类),并且效果很好。 But now I want to pass an object of a BowlingGame to another class, called ScoreCalculator. 但是现在我想将BowlingGame的对象传递给另一个类,称为ScoreCalculator。

The header file looks like: 头文件看起来像:

#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

And the implementation looks like: 实现看起来像:

#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
}

I would like to save the 'BowlingGame object' in the instance var game, but for some reason my console application crashes. 我想将'BowlingGame对象'保存在实例var游戏中,但是由于某些原因,我的控制台应用程序崩溃了。 I've no idea what I'm doing wrong. 我不知道我在做什么错。 The failure is in the rule: * game = gamse; 失败是在规则中: * game = gamse; I looked up some examples on the internet, but can't find a solution. 我在互联网上查找了一些示例,但找不到解决方案。

Your problem here is that you aren't allocating your pointer. 这里的问题是您没有分配指针。 Why don't you just define "game" as BowlingGame game; 您为什么不将“游戏”定义为BowlingGame game; in the header? 在标题中? This way your other code will just work. 这样,您的其他代码即可正常工作。 It will mean that the BowlingGame structure is "copied" into the one in the class but this sounds to be what you are after. 这将意味着BowlingGame结构已“复制”到该类中,但这听起来就是您所追求的。

//* game = gamse; this fails

you haven't allocated anything for game . 你没有为game分配任何东西。 It is just a pointer not pointing to anything valid yet. 它只是一个指针,尚未指向任何有效的指针。 You have to create a new Game object for it to point to. 您必须创建一个新的Game对象以使其指向。

Do it like this 像这样做

game = new Game(gamse);

Assuming Game has an accessible copy constructor. 假设Game具有可访问的副本构造函数。

Also Don't forget to delete game in your destructor or earlier if you don't need it any more. 另外,如果您不再需要delete游戏,请不要忘记delete析构函数中的游戏。 Or even better use a smart pointer for `game. 甚至最好将智能指针用于游戏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM