我不明白两者的意义。


当前回答

声明:“在某处,存在一个foo。”

定义:“…就是这儿!”

其他回答

变量的声明是为了通知编译器以下信息:变量的名称,它持有的值的类型和初始值(如果有的话)。也就是说,声明给出了关于变量属性的详细信息。然而,变量的定义说的是变量存储在哪里。也就是说,变量的内存是在定义变量时分配的。

你不能用最一般的术语说,声明是一个没有分配存储空间的标识符,而定义实际上是从声明的标识符分配存储空间吗?

一个有趣的想法是:只有类或函数与类型信息链接起来,模板才能分配存储空间。那么模板标识符是声明还是定义呢?它应该是一个声明,因为没有分配存储空间,您只是在对模板类或函数进行“原型化”。

声明:“在某处,存在一个foo。”

定义:“…就是这儿!”

声明是在未分配值或对象的情况下创建原语或对象引用变量或方法。 int; Final int a;

定义意味着分别为值或对象赋值 Int a =10;

初始化意味着为各个变量或对象分配内存。

从c++标准文档中添加定义和声明示例(来自3.1节声明和定义)

定义:

int a;                       // defines a
extern const int c = 1;      // defines c
int f(int x) { return x+a; } // defines f and defines x
struct S { int a; int b; };  // defines S, S::a, and S::b
struct X {                   // defines X
    int x;                   // defines non-static data member x
    static int y;            // DECLARES static data member y
    X(): x(0) { }            // defines a constructor of X
};
int X::y = 1;                // defines X::y
enum { up, down };           // defines up and down
namespace N { int d; }       // defines N and N::d
namespace N1 = N;            // defines N1
X anX;                       // defines anX

声明:

extern int a;                 // declares a
extern const int c;           // declares c
int f(int);                   // declares f
struct S;                     // declares S
typedef int Int;              // declares Int
extern X anotherX;            // declares anotherX
using N::d;                   // declares d