Didn"t forge 2009-09-11 12:27 采纳率: 25%
浏览 584
已采纳

定义和声明之间有什么区别?

The meaning of both eludes me.

转载于:https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration

  • 写回答

23条回答 默认 最新

  • MAO-EYE 2009-09-11 12:43
    关注

    A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:

    extern int bar;
    extern int g(int, int);
    double f(int, double); // extern can be omitted for function declarations
    class foo; // no extern allowed for type declarations
    

    A definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:

    int bar;
    int g(int lhs, int rhs) {return lhs*rhs;}
    double f(int i, double d) {return i+d;}
    class foo {};
    

    A definition can be used in the place of a declaration.

    An identifier can be declared as often as you want. Thus, the following is legal in C and C++:

    double f(int, double);
    double f(int, double);
    extern double f(int, double); // the same as the two above
    extern double f(int, double);
    

    However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.


    Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
    At 3.1/2, C++03 says:

    A declaration is a definition unless it [...] is a class name declaration [...].

    3.1/3 then gives a few examples. Amongst them:

    [Example: [...]
    struct S { int a; int b; }; // defines S, S::a, and S::b [...]
    struct S; // declares S
    —end example
    

    To sum it up: The C++ standard considers struct x; to be a declaration and struct x {}; a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)

    Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(22条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路