【问题标题】:Arrays initialization on constructors构造函数上的数组初始化
【发布时间】:2011-06-12 19:52:39
【问题描述】:

我正在尝试将程序转换为 OOP。该程序适用于几个数组:

int tipoBilletes[9] = { 500,300,200,100,50,20,10,1,2 };
int cantBilletes[9] = {0};

所以对于我的转换,我在头文件中声明:

int *tipoBilletes;
int *cantBilletes;

在我写的构造函数中

tipoBilletes = new int[9];
cantBilletes = new int[9];

tipoBilletes[0] = 500;
tipoBilletes[1] = 300;
tipoBilletes[2] = 200;
...

效果很好。

我的问题是,有没有办法像在 Java 中一样初始化它?

int[] tipoBilletes = new int[]{ 500,300 };

而不是必须一个一个地设置每个元素?

【问题讨论】:

  • 直到新版本的 C++ 出来。但是你应该使用std::vector,而不是new[]。另外,将它从固定大小的数组更改为动态数组有什么好处?
  • 仍然无法理解如何在没有旧 C++ 中的默认构造函数的情况下拥有像普通的本地对象数组这样简单的东西......他们有吗,比如,做C++03的时候忘记了,还是什么?
  • 好吧,我使用了动态数组,因为我认为我可以像 java 一样进行初始化
  • @Kos:是什么让你觉得不可能?
  • @BoundaryImposition 抱歉,我真的不记得我的意思了,已经有一段时间了。

标签: c++ arrays oop constructor initialization


【解决方案1】:

如果你使用 std::vector 你可以使用boost::assign:

#include <vector>
#include <boost/assign/std/vector.hpp>  
//... 
using namespace boost::assign;
std::vector<int> tipoBilletes;
tipoBilletes += 500, 300, 200, 100, 50, 20, 10, 1, 2;

另一方面,如果固定大小的数组很小且大小不变,则应考虑使用它。

【讨论】:

    【解决方案2】:

    不,但您不一定需要独立写出每个作业。另一种选择是:

    const int TIPO_BILLETES_COUNT = 9;
    const int initialData[TIPO_BILLETES_COUNT] = { 500,200,300,100,50,20,10,1,2 };
    std::copy(initialData, initialData + TIPO_BILLETES_COUNT, tipoBilletes);
    

    (请注意,您几乎肯定应该为此使用std::vector 而不是手动动态分配。初始化与std::vector 没有什么不同,尽管一旦您使用了resized 它。)

    【讨论】:

    • 实际上,对于std::vector 选项,您可以使用其构造函数初始化向量,该构造函数采用一对迭代器而不是std::copy
    • @Fred:是的,你也可以这样做!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2011-05-02
    相关资源
    最近更新 更多