在构造函数中初始化数组

时间:2016-03-03 06:45:19

标签: c++ arrays

我是一名JavaScript程序员,他试图通过将我的JavaScript类移植到c ++来学习c ++。我很快发现c ++数组中的数组与JavaScript中的数组非常不同。

我班级的成员有数组属性。我在构造函数中初始化数组时遇到问题。这是我的代码。

set_log()

我不知道如何修复最后一部分。我已经乱七八糟了。似乎没什么用。其余的代码很好,我只是得到1个关于构造函数的错误。

我正在使用g ++进行编译。

2 个答案:

答案 0 :(得分:0)

我建议使用std::vector而不是普通的C array,特别是如果你来自javascript。

因此您可以修改代码:

class Name {
  public:
     Name(unsigned int);
     unsigned int getArraySize();
     std::vector<unsigned int> getArray();

  private:
    std::vector<unsigned int> _array;
} 

(在C ++中,首先声明公共成员(最常用的公共API)然后是类的私有成员是一种惯例。通常成员变量具有命名约定,如我使用的_或{ {1}},以区分它们。)

m_

构造函数将创建一个unsigned int Name::getArraySize() { return _array.size(); } std::vector<unsigned int> getArray() { std::vector<unsigned int> outArray; outArray = _array; return outArray; } Name::Name(unsigned int len) : _array(len) { } 维数组,您可以在http://en.cppreference.com/w/cpp/container/vector/vector查看可用的构造函数。
您可以稍后更改数组的长度,将pushing元素更改为向量,或resizing。使用len访问元素时,请注意保留[i]

函数i < _array.size()返回数组中的元素数。 std ::是标准模板库的命名空间,可用于所有C ++编译器。 getArraySize是STL中容器(std :: vector)长度的命名。

函数'getArray'应该返回数组的副本,我写了一个简短的版本,函数的短版本是size

答案 1 :(得分:-1)

您的代码固定为类似C ++(更像C):

class Name {
  private:
    unsigned int *array;

  public:
    unsigned int *getArray();
    Name(unsigned int);
}
//I'm defining everything outside the class because I'm told that's good practice
unsigned int *Name::getArray() {
  return this->array;
}
//this is the problem
Name::Name(unsigned int length) {
  this->array = new unsigned int [length];
}

现在更多的C ++方式:

class Name {
  private:
    std::vector<unsigned int> array;

  public:
    std::vector<unsigned int> getArray(); // Do not worry about optimizations here; check RVO
    Name(unsigned int);
}
//I'm defining everything outside the class because I'm told that's good practice
std::vector<unsigned int> Name::getArray() {
  return array;
}
//this is the problem
Name::Name(unsigned int length) {
  // this line is just to allocate the space for the array, but please keep in ming that you can simply add elements with push_back and the array will grow itself without your explicit memory allocation
  array.resize(length);
}

在第一种情况下,您可以定义指针,例如在一个内存位置的地址,它将保存数组,在第二种情况下,你声明一个对象,它将为你处理内存(或多或少)。

同时看看矢量类:

Vector c++

初学者的一条建议:尝试学习和使用C ++容器(来自STL,BOOST),通常实现非常好并且你没有冒险在脚下射击(指针是“危险的”) ,但是当你学习语言时,你会发现它非常有用和强大。)

相关问题