首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的size函数返回0?

我的size函数返回0?
EN

Stack Overflow用户
提问于 2014-02-22 09:57:24
回答 1查看 136关注 0票数 0

标题

代码语言:javascript
复制
#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 

正文

代码语言:javascript
复制
#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和<<。你知道它为什么输出0吗?

EN

回答 1

Stack Overflow用户

发布于 2014-02-22 10:00:25

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

代码语言:javascript
复制
IntVector(6, 4); 

您想要创建一个对象,如下所示:

代码语言:javascript
复制
IntVector testing(6, 4); 

然后it works

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21948614

复制
相关文章

相似问题

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