Declare And Define
Possible Duplicate:
What is the difference between a definition and a declaration?
I am very confused in these two terms for variables. In some books it seems to be same, but in some books its quite different. Can anyone tell me, what is the meaning of declaration of variables or functions and what is the meaning of definition of variables or functions?
Declaring is like telling the machine that you want say for example, the variable "x" to exist, you can also set it to something.
Defining a variable is setting it to something.
(could be wrong, this is the way I think of it)
A declaration tells the compiler that something exists, but doesn't necessarily provide its code or value. For example, if you declare a function:
void foo();
you're telling the compiler the name of the function, and its arguments (none in this case) and return type, so that it can properly compile calls to the function — even though the function's actual code hasn't been provided yet. Elsewhere in your program, perhaps in a different source file, you provide a definition:
void foo() {
std::cout << "Hello, world!" << std::endl;
}
A definition also acts as a declaration, if the thing you're defining hasn't been declared already.
Generally you put definitions in source files, and declarations in header files so that they can be "seen" by other source files besides the one that contains the definition. However, in C++, when you write a class:
class Blah {
public:
void blah();
private:
int x;
};
That's a definition of the class, which contains declarations of its members. Class definitions typically go in header files, though definitions of the member functions typically don't (aside from template and inline functions).
You may find it informative to read this answer about how compilation and linking works.
链接地址: http://www.djcxy.com/p/40634.html上一篇: 对宣言,定义感到困惑
下一篇: 声明和定义