如何将我编写的对象传递给另一个类的构造函数?

问题描述 投票:2回答:1

我正在实现一个Duplicator类,它将允许我复制Game对象。我需要能够创建与我拥有的游戏对象相同的游戏对象。这存在于棋盘游戏的一个较大实现中,其中包括其他几个类,例如Board and Space。

我有两个Duplicator类文件:

Duplicator.h

#ifndef DUPLICATOR_H
#define DUPLICATOR_H

#include <Rcpp.h>
#include <stack>
#include "Game.h"

using namespace Rcpp;


class Duplicator {
private:
  Game gameObj = Game(5);
public:
  Duplicator(Game g);
  // Game genDuplicate();
};
#endif

Duplicator.cpp

#include <Rcpp.h>
#include <vector>
#include "Game.h"
#include "Duplicator.h"

using namespace Rcpp;




Duplicator::Duplicator(Game g){
  gameObj = g;
}



RCPP_EXPOSED_CLASS(Duplicator)
  RCPP_MODULE(duplicator_cpp) {

    class_<Duplicator>("Duplicator")
    .constructor<Game>()
    ;

我一直收到的错误是:

没有匹配的构造函数,无法初始化'Game'

游戏类包含在两个文件中。

Game.h

#ifndef GAME_H
#define GAME_H

#include <Rcpp.h>

using namespace Rcpp;

class Game {
private:
  int id;
public:
  Game(int n);
};

#endif

Game.cpp

#include <Rcpp.h>
#include "Game.h"

using namespace Rcpp;

Game::Game(int n){
  id = n;
}


RCPP_EXPOSED_CLASS(Game)
  RCPP_MODULE(game_cpp) {

    class_<Game>("Game")
    .constructor<int>()
    ;
  }

我不太确定我需要做什么。似乎我需要在Duplicator类中提供Game的构造函数。

c++ rcpp
1个回答
0
投票

至少在要使用该类作为参数或在其他编译单元中返回类型时,必须将RCPP_EXPOSED_CLASS(...)移至头文件。否则编译器不知道例如Game可以转换为SEXP,反之亦然。

© www.soinside.com 2019 - 2024. All rights reserved.