gpt4 book ai didi

c++ - 返回从常量指针 vector 生成的指针的函数

转载 作者:行者123 更新时间:2023-11-28 03:28:53 29 4
gpt4 key购买 nike

我无法找到作业的解决方案。这是我正在尝试做的事情:我有一个存储在 vector 中的对象列表。称为“AvailableObjects”的 vector 是全局声明的。

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()));
}

上面的代码是我想要使用的。我需要随机选择存储在 vector 中的对象之一,并将该对象的指针返回给调用该函数的任何对象。但是,这无法完成,因为 vector 中的对象是 const Object*,而不是简单的 Object*。这是一项家庭作业,所以我不能修改 const 值,它们的原型(prototype)必须保持不变。最后,我将分享对象类。它有一个专门用于在传递 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 函数返回一个 Object* 使用我可用的 const Object* vector 。

最佳答案

vector 是零索引的,所以 AvailableObjects.at 的有效范围是0 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);

关于c++ - 返回从常量指针 vector 生成的指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148627/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com