我是C++的新手,我在OCaml和Python方面有更多的经验.我想通过制作一个播放"Morpion Solitaire"的程序来学习C++.我的开始有点困难.
在以下代码中:
typedef enum {NORTH, NORTHEAST, EAST, SOUTHEAST} direction;
char deltax[4] = { 0, 1, 1, 1};
char deltay[4] = { 1, 1, 0, -1};
class Coords {
private:
char x,y;
public:
Coords(char xx,char yy){
x = xx;
y = yy;
};
char get_x() const { return x;}
char get_y() const { return y;}
};
class Line {
private:
Coords orig;
direction dir;
Coords newcross;
public:
Line(char x1, char y1, direction d, char x2, char y2) {
orig = Coords(x1,y1);
dir = d;
newcross = Coords(x2,y2);
};
Coords nthpoint(char n) {
char x,y;
x = orig.get_x() + n*deltax[dir];
y = orig.get_y() + n*deltay[dir];
return Coords(x,y);
};
};
Run Code Online (Sandbox Code Playgroud)
编译器告诉我这个:
nico@gaston:~/Travail/Cplusplus/morpion++$ g++ -c morpion.cc
morpion.cc: In constructor ‘Line::Line(char, char, direction, char, char)’:
morpion.cc:29:57: error: no matching function for call to ‘Coords::Coords()’
Line(char x1, char y1, direction d, char x2, char y2) {
^
morpion.cc:29:57: note: candidates are:
morpion.cc:11:3: note: Coords::Coords(char, char)
Coords(char xx,char yy){
^
morpion.cc:11:3: note: candidate expects 2 arguments, 0 provided
morpion.cc:6:7: note: Coords::Coords(const Coords&)
Run Code Online (Sandbox Code Playgroud)
我不明白这个消息.我为类提供了一个2参数构造函数Coords,但编译器一直告诉我orig = Coords(x1,y1)用0参数调用构造函数.
我错过了什么 ?
备注:我最初将Coords和Line的声明放在不同的文件中,并认为我没有使用正确的#include,但将所有内容放在一个文件中并没有解决问题...
Line(char x1, char y1, direction d, char x2, char y2)
: orig(x1,y1), dir(d), newcross(x2, y2) {}
Run Code Online (Sandbox Code Playgroud)
Coords没有默认构造函数.您的原始代码首先尝试默认构造orig,然后为其分配新值.但由于缺少默认构造函数,第一步失败.
您遇到的问题是必须在进入构造函数体之前构造所有类成员和低音.因为在编译器添加了隐式构造之后,构造函数实际上是什么样子
Line(char x1, char y1, direction d, char x2, char y2): orig(), dir(), newcross() {
orig = Coords(x1,y1); // this is assignment not construction
dir = d; // this is assignment not construction
newcross = Coords(x2,y2); // this is assignment not construction
};
Run Code Online (Sandbox Code Playgroud)
这不是问题,dir因为它可以隐式构造但Coords不是这样orig()并且newcross()失败.
要解决此问题,您需要使用成员初始化列表并使用类似的构造函数
Line(char x1, char y1, direction d, char x2, char y2) : orig(x1, y1), newcross(x2, y2), dir(d) {}
Run Code Online (Sandbox Code Playgroud)