【发布时间】:2015-08-20 07:26:27
【问题描述】:
我在将派生类传递给接受基类作为参数的函数时遇到问题。基类由“障碍物”组成,这些“障碍物”将被放置在“板”上 void Board::setvalue(int length, int width, Obstacle& barrier);
但是,这会导致编译器给出“no known conversion for argument...”错误。在网站上阅读时,我发现我应该将派生对象作为 const 传递,但这会导致问题,因为无法将 const 分配给电路板(因为它包含指向非 const 障碍的指针)。
反过来,将 Board 更改为持有 const Obstacles 会导致项目其他地方出现很多问题,尤其是对于 Board 和 Obstacle 的操作员
我尝试将对象作为 const 传递,然后使用 Obstacle ob = new barrier(const 障碍) 但这使它们成为通用的 Obstacle 对象而不是 Player/Barrel/Wall 对象。
有没有办法将这些对象作为非常量传递或将它们分配为非常量?我尝试使用 const_cast() 但这会导致未定义的行为。
函数调用示例:
Board_->setvalue(x, y, Player(data, moveable, x, y));
这是我的代码:
基类
class Obstacle
{
public:
Obstacle* _properlyinitialized;
string Name;
bool Moveable;
int x;
int y;
Obstacle();
Obstacle(string Name, bool Moveable, int x, int y);
virtual ~Obstacle();
bool properlyInitialized();
friend std::ostream& operator<<(std::ostream& stream, Obstacle& Obstacle);
};
派生类的一个例子(其他派生类还没有特殊功能)
class Player: public Obstacle
{
public:
Player():Obstacle(){};
Player(string Name, bool Moveable, int x, int y):Obstacle(Name, Moveable, x, y){this->_properlyinitialized = this;};
~Player(){};
/*void Moveleft();
void Moveright();
void Moveup();
void Movedown();*/
};
Board 类头
class Board
{
private:
Board* _properlyinitialized;
int length;
int width;
Obstacle * * * playfield;
public:
/*
**ENSURE(this->properlyInitialized(),
"Object wasn't initialized when calling object");
*/
Board();
Board(int length, int width);
~Board();
bool properlyInitialized();
/*
**REQUIRE(this->properlyInitialized(),
"Object wasn't initialized when calling properlyinitialized");
*/
void clear();
const int getLength();
const int getWidth();
Obstacle*** getBoard();
Obstacle* getTile(int length, int width);
void setvalue(int length, int width, Obstacle& obstacle);
friend std::ostream& operator<<(std::ostream& stream, Board& Board);
};
std::ostream& operator<<(std::ostream& stream, Board& Board);
最后是 setvalue 函数。
void Board::setvalue(int length, int width, Obstacle& obstacle)
{
this->playfield[length][width] = &obstacle;//value;
return;
}
如果需要,我很乐意提供更多代码。
【问题讨论】:
-
代码越简洁越好。
-
我认为您需要使用指针。这使得保留原始类成为可能。
-
@davidhigh 我尝试对其进行一些清理,更好地分离部分并删除其他派生类,因为此时它们实际上是重复的。现在好看了吗?
-
@FelixNeijzen:很好,现在看起来好多了。但是对于一个真正的最小示例,您可以将所有构造函数、析构函数、不相关的 getter、setter 和数据成员放在一边(然后您可能会得到 20 行代码)。
标签: c++ inheritance pass-by-reference derived-class