Lin*_*äck 1 c++ circular-dependency forward-declaration
我的班级遇到了一些问题,因为它们彼此依赖,如果没有宣布另一个,就不能宣布.
class block: GtkEventBox {
public:
block(board board,guint x,guint y): image("block.png") {
this.board = board;
this.x = x;
this.y = y;
board.attach(this,x,y,x+1,y+1);
}
void move(guint x,guint y) {
board.remove(this);
this.x = x;
this.y = y;
board.attach(this,x,y,x+1,y+1);
}
private:
guint x, y;
board board;
GtkImage image;
};
class board: Gtk::Table {
public:
board(): Gtk::Table(25,20) {
blocks_c = 0;
}
void addBlock(guint x,guint y) {
blocks_a[blocks_c++] = new block(this,x,y);
}
private:
block* blocks_a[24];
int blocks_c;
};
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,"块"类需要知道"板"是什么,反之亦然.提前致谢!
gat*_*fax 10
在"阻止"之前定义"board"并向前声明"block"类.此外,将板函数的实现移出类定义.
// forward declare block class
class block;
// declare board class
class board: Gtk::Table {
public:
board();
void addBlock(guint x,guint y);
private:
block* blocks_a[24];
int blocks_c;
};
// declare block class
class block: GtkEventBox {
public:
block(board board,guint x,guint y);
void move(guint x,guint y);
private:
guint x, y;
board board;
GtkImage image;
};
// define member functions (implementation) here...
Run Code Online (Sandbox Code Playgroud)
使用此行向前声明您的block班级board:
类块;
在两个类的声明之后放置函数体的代码.向前声明您的类并不能使其所有函数可用,它只是允许编译器知道这样的类存在.它只允许使用指向这样一个类的指针(因为指针类型的大小不依赖于类的布局).