我希望你们中的一位能向我解释为什么编译器要求我在编译单元中重新定义一个静态固定长度数组,尽管我已经在头文件中这样做了。这是一个例子:
我的类.h:
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass {
private:
static char myPrecomputeTable[256];
}
#endif
我的类.cpp
#include "MyClass.h"
char MyClass::myPrecomputeTable[256];
如果我删除 MyClass.cpp 中的重新定义,链接器会提示 myPrecomputeTable 未定义。语法似乎是多余的。谁能向我解释为什么编译器/链接器需要定义?
编辑:
抱歉,我想我不清楚我对什么感到困惑。我理解声明/定义的概念,更多的是定义我觉得有趣的数组的大小。在定义和声明中,我必须定义看起来多余的大小。
编辑:
我做了更多的挖掘,结果发现这个主题的许多方法都是编译器友好的。 编译:
MyClass.h
class MyClass {
static char myPrecomputeTable[256];
};
MyClass.cpp
char MyClass::myPrecomputeTable[256];
编译:
MyClass.h
class MyClass {
static char myPrecomputeTable[];
};
MyClass.cpp
char MyClass::myPrecomputeTable[256];
编译:
MyClass.h
class MyClass {
static char myPrecomputeTable[256];
};
MyClass.cpp
char MyClass::myPrecomputeTable[];
不编译:
MyClass.h
class MyClass {
static char myPrecomputeTable[512];
};
MyClass.cpp
char MyClass::myPrecomputeTable[256];
大小必须在头文件或类或两者中定义,但编译器足够聪明,可以阻止大小冲突。
最佳答案
在标题中:
class MyClass {
private:
static char myPrecomputeTable[256];
}
这是一个声明。
在 .cpp 中:
char MyClass::myPrecomputeTable[256];
是一个定义。
A declaration provides basic attributes of a symbol: its type and its name.
A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored.
Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols.
了解两者之间区别的一个很好的链接:http://www.cprogramming.com/declare_vs_define.html
来自标准:
3.1 Declarations and definitions [basic.def]
A declaration may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. If so, the declaration specifies the interpretation and attributes of these names. A declaration may also have effects including:
- a static assertion (Clause 7),
- controlling template instantiation (14.7.2),
- use of attributes (Clause 7), and
- nothing (in the case of an empty-declaration).
A declaration is a definition unless it declares a function without specifying the function’s body, it contains the
extern
specifier or a linkage-specification and neither an initializer nor a function-body, it declares a static data member in a class definition, it is a class name declaration, it is an opaque-enum-declaration, or it is a typedef declaration, a using-declaration, a static_assert-declaration, an attribute-declaration, an empty-declaration, or a using-directive.
关于c++ - 为什么需要重新定义固定大小的静态数组/有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17996729/