【问题标题】:c++ pointer to array of objects works in gnu c++ but not visual studioc++ 指向对象数组的指针适用于 gnu c++ 但不适用于 Visual Studio
【发布时间】:2013-04-01 05:40:50
【问题描述】:

我正在尝试使用指向 C++ 中自定义对象数组的指针。以下代码在使用 cygwin 的 gnu 编译器的 eclipse 上编译并运行良好。但是代码在 Visual Studio 中给出了编译错误。

错误

class 'Levels' has an illegal zero-sized array

上线

Structure *mStructres[];

完整代码

/*
 * Levels.h
 */

#include "objects/Structure.h"

#ifndef LEVELS_H_
#define LEVELS_H_

class Levels{

public:

    //other public members

    void reInitialize();
    Levels();
    ~Levels();


private:
    //other private members
    Structure *mStructres[];
};

#endif /* LEVELS_H_ */

/////////////////////////////////////
/*
 * Levels.cpp
 */
#include "Levels.h"

Levels::Levels() {
}

Levels::~Levels() {

}

void Levels::reInitialize() {
    mStructres[size];
                for (int i = 0; i < jStructeresArr.size(); i++) {
                mStructres[i] = new Structure(obj1, obj2,
                            obj3);
                }
}

我尝试将行改为

Structure *mStructres;

但后来我在重新初始化方法中的这些行出现错误

mStructres[size];
            for (int i = 0; i < jStructeresArr.size(); i++) {
            mStructres[i] = new Structure(obj1, obj2,
                        obj3);
            }

我做错了什么?这是跨平台开发的正确方法吗?

更新 在这个阶段我宁愿不使用向量或标准模板。

【问题讨论】:

  • 这是一个指针数组(大小未知)。
  • 是的,我想要一个动态数组。
  • 使用std::vector
  • std::vector&lt;Structure*&gt; 或者如果你想做 C 方式,Structure**
  • 这不是合法的 C++。它适用于 GCC,因为 GCC 开发人员已决定允许它作为非标准扩展。它在 Visual Studio 中不起作用,因为 VS 不支持该特定的非标准扩展。

标签: c++ visual-c++ pointers g++


【解决方案1】:

Structure *mStructres[]; 可能被其中一个编译器解释为Structure **mStructres。(编辑:这可能不正确,请参阅 cmets 中的更正)它只是一个指向结构指针的指针。请注意,实际上并没有为它分配任何指向的存储空间(除了单个指针),因此当您为其分配任何内容时,您只是将其写入随机内存。

mStructres[size];       // This does nothing, it _could_ cause a crash... 
                        //  but is otherwise the same as the next statement
42;
for (int i = 0; i < jStructeresArr.size(); i++)
    mStructres[i] = new Structure(obj1, obj2, obj3);

我怀疑你想做的只是重新创建你的指针数组。

void Levels::reInitialize() {
    for (int i=0; i< jStructeresArr.size(); i++) {
        delete mStructres[i];      // Don't leak memory
        mStructres[i] = new Structure(obj1, obj2, obj3);
    }
}

您的构造函数中还需要以下行。 (灵感来自here

    mStructres = new Structure*[jStructeresArr.size()];

如果 jStructeresArr.size() 发生变化,你有很多工作要做。所以如果有这种可能,我强烈建议你放弃这个,只使用 std::vector 或 std::list。

【讨论】:

  • "Structure *mStructres[]; 可能被解释为 Structure **mStructres" -- 不,我不认为是这种情况。我相信这是 C99 中称为“灵活数组”的特性,即使编译为 C++,GCC 也允许使用它。
  • @BenjaminLindley:在语言中特别允许有什么讨厌的黑客攻击......以前从未听说过这种废话。
  • 我进行了您指定的更改。编译错误消失了,但现在它在其他地方抛出链接器错误“LNK2019 unresolved symbol”在一个完全不同的位置。我认为错误是因为我所做的更改。有任何想法吗?谢谢。
  • @user603125:鉴于此处涉及的更改,链接错误几乎可以肯定是无关的。需要许多更具体的细节。 (也许作为一个单独的问题......但链接错误通常非常本地化到您的特定代码,所以它们经常误入offtopic-space)
  • 将此标记为正确以解决编译错误。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2016-12-29
  • 2021-02-25
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 2013-04-30
  • 2014-01-25
  • 2018-04-02
相关资源
最近更新 更多