operator = isn未被调用,分段错误

时间:2016-12-02 13:54:08

标签: c++ segmentation-fault operator-overloading

我有一个简单的类游戏,它包含两个字段int Nbool isVerbalOn。我为这个类编写了一个operator =(复制赋值运算符),但是当我尝试使用该运算符时,我得到一个"分段错误(核心转储)"错误,并且运营商=没有被叫,即我没有看到"在游戏oeprator ="打印。下面附上课程和主要课程,以方便您:

Game.h:

#ifndef GAME_H_
#define GAME_H_

#include <iostream>

using namespace std;

class Game {
    private:
        int N;
        bool isVerbalOn;
    public:
        Game(char* configurationFile); // implemented and works perfectly
        void init(); // implemented and works perfectly
        void play(); // empty implementation
        void printState(); // implemented
        void printWinner(); // emtpy implementation
        void printNumberOfTurns(); // empty implementation
        Game & operator=(const Game &game_);
        ~Game(); // implemented and works perfectly
};

#endif

Game.cpp:

#include "../include/Game.h"
#include <fstream>
#include <iterator>
#include <sstream>

// .. functions implemented

Game &Game::operator=(const Game &game_) {
    cout << "Game operator=" << endl;
    if(this == &game_) {
        return *this;
    }
    N = game_.N;
    isVerbalOn = game_.isVerbalOn;
    return *this;
}

main.cpp中:

#include <iostream>
#include "../include/Game.h"

using namespace std;

int main(int argc, char **argv) {
    char* configurationFile = argv[1];

    Game game = Game(configurationFile);
    game.init();
    Game initializedGame = game; // operator= isn't called
    game.play();

    cout << endl;
    cout << "----------" << endl;
    cout<<"Initial State:"<<endl;
    initializedGame.printState();
    cout<<"----------"<<endl;
    cout<<"Final State:"<<endl;
    game.printState();
    return 0;
}

Makefile编译时没有错误或警告,输出为:

----------
Initial State:
Deck: 2H 2S QD
Alice:2C 3D 3S JH QH KC AH 
Bob:3C JS QC KH KS AD AS 
Charlie:2D 3H JC JD QS KD AC 
----------
Final State:
Deck: 2H 2S QD
Alice:2C 3D 3S JH QH KC AH 
Bob:3C JS QC KH KS AD AS 
Charlie:2D 3H JC JD QS KD AC 
Game destructor
Deck destructor
Segmentation fault (core dumped)

如您所见,游戏运营商中的打印=&#34;游戏运营商=&#34;本应该在其他任何事情之前打印出来,但这并不会发生。

P.S。我在SOF上检查了很多关于此问题的其他问题,并没有找到任何帮助我的东西。感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:2)

Game initializedGame = game; // operator= isn't called

这将调用复制辅助器。

在Game.cpp中添加以下复制构造函数

Game(const Game &game_) {
    cout << "Game copy ctro" << endl;
    N = game_.N;
    isVerbalOn = game_.isVerbalOn;
}

优选地

Game(const Game &game_):N(game_.N), isVerbalOn(game_.isVerbalOn)
{}

答案 1 :(得分:1)

Game initializedGame = game; // operator= isn't called

不,它不会。

这是一个声明和初始化,调用复制构造函数。

尽管此行中=字符的外观如此,但赋值运算符与它无关。