0

我在为我的作业找到解决方案时遇到了麻烦。这就是我想要做的:我有一个存储在向量中的对象列表。称为“AvailableObjects”的向量是全局声明的。

vector<const Object*> AvailableObjects; 

...

void       read_obj_file(const char* filename){
ifstream infile (filename, ios::in);

while(!infile.eof()) {
        char name[20];
        int attribute;
        int size = 0;
        infile >> name >> attribute >> size;
        AvailableObjects.push_back(new Object(name, attribute, size));
        }
 infile.close();
 return;
 }

读取对象后,我需要编写一个函数来生成单个对象,并将其推送到用户可用的对象堆栈中。

Object*     generate_object(){
        return AvailableObjects.at(rand_in_range(1,AvailableObjects.size()));
        }

上面的代码是我想要使用的。我需要随机选择一个存储在向量中的对象,并将该对象的指针返回给任何调用函数的对象。但是,这无法做到,因为向量中的对象是 const Object*,而不是简单的 Object*。这是一个家庭作业,所以我不能修改 const 值,它们的原型必须保持不变。最后,我将分享对象类。它有一个构造函数,专门用于在传递 const Object* 时创建一个新对象,但我无法使构造函数按预期工作。

/**
 * object.h
 *
 * Objects are immutable (read-only) once instantiated.
 */
#ifndef OBJECT_H
#define OBJECT_H

#include<string>
    using std::string;

class object{
    private:
    string _name;
    int    _attribute;
    int    _size;

    public:
    // Constructor
    Object(string name, int attribute, int size){
        _name  = name;
        _attribute = attribute;
        _size  = size;
    }
    Treat(const Treat& t){
        _name  = t._name;
        _attribute = t._attribute;
        _size  = t._size;
    }
    // Accessors
    string name() const {return _name;}
    int    attribute()const {return _attribute;}
    int    size() const {return _size;}
    };

    #endif

这里还有一个在整个代码中显示的函数,它在特定范围内选择一个随机数。

    int rand_in_range(int low, int high){
        init_rand();
        high < low ? throw "Invalid range." : 0 ;
        int modbase = ((high+1) - low);
        int ans = 0;
        ans = rand() % modbase + low;
        return ans;
        }

感谢您的任何回复,我将积极关注此内容,因此,如果有人有任何问题,我将很乐意回复。再次总结一下,我需要帮助来让我的 generate_object 函数使用我可用的 const Object* 的向量返回一个 Object*。

4

2 回答 2

1

首先,范围应该从零开始,而不是从一开始。其次,您可以像下面的链接一样通过类型转换来删除 const

http://msdn.microsoft.com/en-US/library/bz6at95h(v=vs.80).aspx

于 2012-10-30T22:46:01.623 回答
1

向量是零索引的,因此 的有效范围AvailableObjects.at0 to AvailableObjects.size()-1

假设Treat(const Treat& t)应该是Object(const Object& t)并且您在转录时犯了错误,那么它不会const Object*像您所说的那样。由于它需要一个 const 引用,而不是 const 指针,因此您必须取消引用您的指针。例如,如果我们想对 AvailableObjects 中的第五个对象进行深拷贝,我们会这样做:

int index = 4; // 0, 1, 2, 3, 4... thus index 4 refers to the fifth item.
const Object* object = AvailableObjects.at(index);
Object* clone = new Object(*object);
于 2012-10-30T23:35:43.483 回答