在C++类中创建一个克隆函数
问题描述:
我目前正在开始为类复制滑动砖拼图的工作分配。自从我使用C++以来已经有几年了,所以我试图重新学习并一次性完成这项任务。我一直在研究生物工程和使用MATLAB,但在我参加的少数计算机科学课程中,我也很难适应C++。在C++类中创建一个克隆函数
我的问题是我必须做的克隆功能。我目前遇到了调试器问题,所以当我尝试运行该程序时,它只是崩溃,我不知道为什么。顾名思义,克隆函数应该创建类对象的克隆。我的代码在下面提供供您参考。
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <list>
using namespace std;
struct move
{
int piece;
char direction;
};
class SBP
{
public:
vector< vector<int> > state;
int width; //columns
int height; //rows
void load(string filename);
void display();
SBP clone();
};
void SBP::load(string filename)
{
int rownum = 1;
char n;
string str;
ifstream file(filename.c_str());
getline(file, str);
width = str[0]-'0';
height = str[2]-'0';
while (getline(file, str))
{
vector<int> row;
for (int i = 0; i < str.size(); ++i)
{
n = str[i];
if (n != ',')
{
if (n == '-')
{
row.push_back((str[i + 1] - '0')*(-1));
i = i + 1;
}
else
{
if (str[i + 1] == ',')
row.push_back(n - '0');
else
{
row.push_back((str[i] += str[i + 1]) - '0');
i = i + 1;
}
}
}
}
state.push_back(row);
rownum = rownum + 1;
}
printf("File has been loaded.\n\n");
}
void SBP::display()
{
int num;
printf("The state of the game is: \n");
printf("%i,%i,\n", width, height);
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
{
num = state[r][c];
printf("%i,", num);
}
printf("\n");
}
printf("\n");
}
SBP SBP::clone()
{
SBP clonestate;
clonestate.width = width;
clonestate.height = height;
for (int r = 0; r < height; ++r)
{
for (int c = 0; c < width; ++c)
clonestate.state[r][c] = state[r][c];
}
return clonestate;
}
int main(int argc, char **argv)
{
string filename = argv[1];
SBP puzzle, clonestate;
puzzle.load(filename);
puzzle.display();
clonestate = puzzle.clone();
clonestate.display();
return 0;
}
我希望有人能帮助我。这只是任务的开始,我不能继续前进,直到我得到修复。谢谢。
答
认为您应该在分配克隆值之前调整大小。
,或者你只是使用默认的拷贝构造函数,只要你没有指针成员
SBP SBP::clone()
{
return *this;
}
+0
克隆功能的一般模式是返回一个指向克隆实例的指针:SBP * SBP :: clone(){return new(* this);}'。 –
那类不应该需要一个克隆功能。它都是基于值的,所以operator =应该足够 – Joe
复制构造函数和赋值操作符应该做你需要的。我唯一能想到的就是你需要一个克隆函数,当你使用继承时,可能不知道你在持什么样的东西。 – user4581301
其实你甚至不需要写一个拷贝构造函数或赋值操作符。至少不要用那种类定义的方式。编译器生成的拷贝构造函数和赋值操作符应该适合你。亲自尝试一下。创建一个SBP,加载它,然后做一个任务。它应该工作。 – Joe