【发布时间】:2016-02-12 22:27:01
【问题描述】:
程序
我使用 Eclipse 来编写、编译、构建和运行这段代码。在 Windows 和 Linux 上都可以。
Card.h
class Card {
private:
static int _palette[][3];
public:
static int (*palette())[3];
};
Card.cpp
#include "Card.h"
int Card::_palette[][3]= {
{168, 0, 32},
{228, 92, 16},
{248, 216, 120},
{88, 216, 84},
{0, 120, 248},
{104, 68, 252},
{216, 0, 204},
{248, 120, 248}
};
main.cpp
#include <iostream>
#include "Card.h"
int main(int argc, char **argv) {
int uniqueColors= sizeof(Card::palette());
std::cout << uniqueColors << std::endl;
return 0;
}
这在我的 Windows10 操作系统上打印 4,在 Debian 8.2 Jessie 上打印 8。
Windows 构建日志
当我使用 MinGW GCC 工具链和 CDT Internal Builder 构建时,这是 64 位 Win10 上的 Eclipse 控制台:
16:53:09 **** Rebuild of configuration Debug for project sizeOf-test ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o Card.o "..\\Card.cpp"
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.cpp"
g++ -o sizeOf-test.exe Card.o main.o -lmingw32
16:53:11 Build Finished (took 1s.934ms)
当我运行程序时,它会打印出4。
Linux 构建日志
这是 64 位 Debian 8.2 Jessie 上的 Eclipse 控制台,使用 Linux GCC 工具链和 CDT Internal Builder:
17:17:57 **** Incremental Build of configuration Debug for project cpp-sizeof-test ****
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o ../main.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o Card.o ../Card.cpp
g++ -o cpp-sizeof-test Card.o main.o
17:17:57 Build Finished (took 327ms)
问题
- 为什么会有差异?
- 如何更改代码以便在每个操作系统上打印成员变量
_palette中正确的数组数量? - 可选:在没有多维数组的情况下,是否有更简洁的方法来实现我的目标?在 C++98 还是 C++11 中?
【问题讨论】:
-
你没有说它在 Linux 上的大小......另外,你确定你的 MinGW 是在 64 位而不是 32 位构建的吗?
4是 32 位应用程序中指针的典型大小,您正在打印sizeof指针 -
AFAIK,mingw 不支持 64 位。
-
@txtechhelp 在Linux上打印
8,在Windows10上打印4 -
你可能想要
std::vector<RGBColor>。 -
@molbdnilo 如果我想在不使用
std::vector的情况下为Windows 制作.exe,我是否只需要更改编译器?我可能最终会使用矢量,但我很好奇如果没有它是否可能。