C++:正确初始化抽象类的构造函数


初始化

抽象类构造函数的正确方法是什么?我在 cc 文件中注释掉了构造函数,它似乎正在工作,我想了解为什么。

董事会。Board.h 是一个抽象类,因为它有 2 个纯虚函数,此处未包含。

class Board {
public:
   Board(size_t width, size_t height)
    : width(width), height(height) {}
   virtual ~Board() {}
....
protected:
//this is line 54
size_t height;
size_t width;
};

My localBoard.h

#include <Board.h>
class LocalBoard : public Board {
public:
  LocalBoard(size_t width, size_t height) :Board(width),Board(height) {}
  ~LocalBoard() {}
 ...
};

LocalBoard.cc

#include <board/LocalBoard.h>
    // commenting this out fixed the error
    //LocalBoard(size_t width, size_t height) {}
error: multiple initializations of constructor

另一方面,有人可以帮助我了解以下警告的含义,它对我的程序有什么后果以及如何解决它?我认为它再次与构造函数有关。

  ./include/board/Board.h: In constructor ‘Board::Board(size_t, size_t)’:
  ./include/board/Board.h:54:9: warning: ‘Board::width’ will be              initialized    after [-Wreorder]
   size_t width;

您已经在此行中提供了类 LocalBoard 的 ctor 的内联实现:

LocalBoard(size_t width, size_t height) :Board(width),Board(height) {}

您不能给同一个 ctor 两次(一次是内联的,一次是在 cc 文件中)。

你需要写

class LocalBoard {
    LocalBoard(size_t width, size_t height) :Board(width, height) {}
};

class LocalBoard {
    LocalBoard(size_t width, size_t height);
}
// probably in the cc file:
LocalBoard::LocalBoard(size_t width, size_t height) : Board(width, height)
{
}

请注意,我将两个基类 ctor 调用Board(width),Board(height)更改为一个基类 ctor 调用Board(width, height)

关于警告,你可以看看g++ -Wreorder有什么意义?。

最新更新