【问题标题】:How do you declare arrays in a c++ header?如何在 c++ 标头中声明数组?
【发布时间】:2010-09-22 00:57:36
【问题描述】:

这与其他一些问题有关,例如:this,以及我的一些其他问题。

this question 和其他人中,我们看到我们可以在一个不错的步骤中声明和初始化字符串数组,例如:

const char* const list[] = {"zip", "zam", "bam"}; //from other question

这可以在没有麻烦的函数实现中完成,也可以在任何范围之外的 .cpp 文件的主体中完成。

我想要做的是将这样的数组作为我正在使用的类的成员,如下所示:

class DataProvider : public SomethingElse
{
    const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};

public:
    DataProvider();
    ~DataProvider();

    char* GetData()
    {
        int index = GetCurrentIndex(); //work out the index based on some other data
        return mStringData[index]; //error checking and what have you omitted
    }

};

但是,编译器抱怨,我似乎无法找出原因。是否可以在类定义的一个步骤中声明和初始化这样的数组?有没有更好的替代品?

【问题讨论】:

  • “implimentation”应拼写为“implementation”

标签: c++ arrays header initialization constants


【解决方案1】:

这在 C++ 中是不可能的。您不能直接初始化数组。相反,您必须给它它的大小(在您的情况下为 4),并且您必须在 DataProvider 的构造函数中初始化数组:

class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    const char * values[SIZEOF_VALUES];

    public:
    DataProvider() {
        const char * const v[SIZEOF_VALUES] = { 
            "one", "two", "three", "four" 
        };
        std::copy(v, v + SIZEOF_VALUES, values);
    }
};

请注意,您必须放弃数组中指针的常量性,因为您不能直接初始化数组。但是您需要稍后将指针设置为正确的值,因此指针需要是可修改的。

如果数组中的值仍然是 const,唯一的方法是使用静态数组:

/* in the header file */
class DataProvider {
    enum { SIZEOF_VALUES = 4 };
    static const char * const values[SIZEOF_VALUES];
};

/* in cpp file: */

const char * const DataProvider::values[SIZEOF_VALUES] = 
    { "one", "two", "three", "four" };

拥有静态数组意味着所有对象都将共享该数组。这样你也节省了内存。

【讨论】:

  • “拥有静态数组意味着所有对象都将共享该数组”这也意味着您可能刚刚破坏了面向对象编程的基本原则。
【解决方案2】:

使用关键字static和外部初始化,使数组成为类的静态成员:

在头文件中:

class DataProvider : public SomethingElse
{
    static const char* const mStringData[];

public:
    DataProvider();
    ~DataProvider();

    const char* const GetData()
    {
        int index = GetCurrentIndex(); //work out the index based on some other data
        return mStringData[index]; //error checking and what have you omitted
    }

};

.cpp 文件中:

const char* const DataProvider::mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"};

【讨论】:

  • 您需要在标头声明中为数组指定大小。
  • 你确定吗?它对我来说很好用(Visual C++ 2005),我之前已经使用过几次了。除非它是标准中未定义的行为(我现在不会查找),否则我相信它会起作用。
  • 您在使用初始化程序时很好。编译器将根据初始化程序中的项目数计算大小。
  • 是的,我认为省略大小是有效的,那么数组是不完整的。但是在标题中,您确实不会知道数组的大小。所以也没有 sizeof 可能 -.-
  • 好吧,由于 OP 使用的是(成员)函数 GetCurrentIndex(),如果它在同一个 .cpp 文件中定义,它可以使用 sizeof 运算符。
【解决方案3】:

你不能这样声明你的数组 (const char* []) 的原因是:

  • 类声明中不能有初始化器,所以
  • 语法const char* [] 没有说明编译器需要为每个实例分配多少空间(您的数组被声明为实例变量)。

此外,您可能希望将该数组设为静态,因为它本质上是一个常量值。

【讨论】:

  • 实际上,const char* [] 确实说明了编译器需要为每个实例分配多少空间——只是一个指向内存的指针。这真的是为什么非静态变量不允许静态数组声明;每个新实例都需要额外的内存分配,而这种处理开销传统上是在构造函数中显式处理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2018-09-27
  • 2016-12-07
相关资源
最近更新 更多