【发布时间】:2012-03-16 00:42:59
【问题描述】:
我的派生类有点问题。基本上我有一个超类Object 和一个派生类UnmovableObject。我正在尝试向派生类添加一个布尔变量,以便以后可以读取它并查看我的对象是否可以移动。我遇到的问题是我将所有对象(超级对象和派生对象)存储到list<Object> inventory 中。每次我从列表中读取值时,我都会为 isFixed() 方法得到一个奇怪的值 (204)。这是代码:
//super class
#pragma once
#include "stdafx.h"
class Object{
public:
Object(); //constructor
Object(const string name, const string description); //constructor
~Object(); //destructor
private:
string nameOfObject; //the name of the room
string objectDescription; //the description of the room
};
//derived class
#pragma once
#include "stdafx.h"
#include "object.h"
//This class creates unmovable objects - the user can't pick them up.
class UnmovableObject : public Object {
public:
UnmovableObject(string name, string description);
UnmovableObject(const Object &object) : Object(object){};
bool isFixed();
private:
bool fixed;
};
//the constructor of this class takes a boolean value (by default true) - the object is fixed in this room
UnmovableObject::UnmovableObject(string name, string description) : Object(name, description){
this->fixed = true;
}
//returns false as the object is not movable
bool UnmovableObject::isFixed(){
return this->fixed;
}
//other class
list<Object> inventory;
我如何使用inventory.push_back(Object/UnmovableObject);,这样当我尝试访问inventory 时,我可以获得所有它们的正确布尔值——true 用于 UnmovableObject; false 为对象。
【问题讨论】:
标签: c++ list inheritance constructor