c++ - 我的大小函数返回 0?

标签 c++

<分区>

标题

#ifndef INTVECTOR_H
#define INTVECTOR_H

using namespace std;
class IntVector{
private:
    unsigned sz;
    unsigned cap;
    int *data;
public:
    IntVector();
    IntVector(unsigned size);
    IntVector(unsigned size, int value);
    unsigned size() const;
};
#endif 

正文

#include "IntVector.h"
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;



IntVector::IntVector(){
    sz = 0;
    cap = 0;
    data = NULL;
}

IntVector::IntVector(unsigned size){
    sz = size;
    cap = size;
    data = new int[sz];
    *data = 0;
}

IntVector::IntVector(unsigned size, int value){
    sz = size;
    cap = size;
    data = new int[sz];
    for(unsigned int i = 0; i < sz; i++){
        data[i] = value;
    }
}

unsigned IntVector::size() const{
    return sz;
}

当我在 Main 中测试我的函数时,(IntVector(6, 4); cout << testing.size() << endl;),我的 testing.size() 测试始终输出 0,而理论上它应该是 6,因为我在 IntVector 函数中分配了 sz 和 cap。关于它为什么输出 0 的任何想法?

最佳答案

看起来你正在创建一个被丢弃在这里的临时文件:

IntVector(6, 4); 

你想创建一个对象,像这样:

IntVector testing(6, 4); 

然后呢works .

关于c++ - 我的大小函数返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21948614/

相关文章:

c++ - sqlite 表代码管理器?

c++ - 在 C++ 中将同一文件加倍间距

c++ - glm::mat4 * glm::mat4 产生不正确的结果?

c++ - 从模板类的实例继承

c++ - 函数 _main 中未解析的外部符号 "cSocket::cSocket(void)"

c++ - 从主 CUDA 声明设备变量

c++ - SHOpenWithDialog 模拟 Windows XP?

c++ - 如何使用opencv setOpenGlDrawCallback函数?

c++ - g++ 在应该产生错误时没有产生错误,例如 "error: variable length array of non-POD element type"

c++ - Qt、Qmake 和 Visual Studio 2013