首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >自己的“动态”向量类

自己的“动态”向量类
EN

Stack Overflow用户
提问于 2014-03-09 08:03:15
回答 1查看 597关注 0票数 1

我很难做我自己的动态向量类..。最后的目标是在c++上模拟堆栈和队列,在向量类上使用类,然后迁移到通过链接列表创建堆栈和队列,但是我在创建向量类时遇到了问题.

因为我不能用默认值创建一个变量,所以我在构造函数上分配它们,但是,它会导致它不能工作,这样.我真的不想用标准库,有什么想法吗?

我的想法是在构造函数中声明数组,然后将其复制到类上的指针声明,但它可以执行int工作.我只能得到第一个元素的值,但其他元素不能.

代码语言:javascript
运行
复制
    class Vector{
    private:
        int *arr;
        int size;
        int inside;
    public:
        Vector(int);
        int length();       // Largo del Arreglo
        int count();        // Numero de elementros adentro
        bool empty();       // Vacio
        bool full();        // Lleno
        int at(int);        // Revisa el N elemento
        int get(int);       // Regresa el n elemento
        bool put(int, int); // Inserta elemento X en n posicicion
        void clean();

};
/// Clase Vector
Vector::Vector(int x){ // Constructor
    int vec[x];
    arr=vec;
    size=x;
    inside=0;
}
// Estado del Vector
bool Vector::empty(){
    if(inside==0){
        return true;
    }
    return false;
}
bool Vector::full(){
    if(inside==size){
        return true;
    }
    return false;
}
int Vector::length(){
    return size;
}
int Vector::count(){
    return inside;
}
// Manipulacion de Datos
int Vector::get(int x){
    int y=at(x);
    put(0,x);
    inside = inside-2;
    return y;

}
int Vector::at(int n){
    int i=arr[n];
    return i;
}
bool Vector::put(int x, int p){
        arr[p]=x;
        inside++;
        return true;
}
void Vector::clean(){
    for(int i=0;i<length();i++){
        put(0,i);
    }
}
EN

Stack Overflow用户

回答已采纳

发布于 2014-03-09 08:05:40

这是行不通的:

代码语言:javascript
运行
复制
int vec[x];
arr=vec;

您正在为一个成员变量分配一个自动局部变量的地址,该变量将在函数退出时保留作用域。从那时起,访问它是未定义的行为。更糟糕的是,这甚至是不可移植的,因为它依赖于变量长度数组的编译器扩展,这是C++标准所不支持的。

您需要使用operator new []动态地分配基本向量--您还需要正确地实现析构函数、赋值操作符和复制构造函数(如果采用完整的gambit、移动分配和移动构造),以正确地遵守第三/五条规则语义。

票数 4
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22279822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档