声明与定义最大的区别就是是否分配存储空间。
1 变量
变量的定义用于为变量分配存储空间,还可以为变量指定初始值。在一个程序中,变量有且只有一个定义。
变量的声明用于向程序表明变量类型与名字。
定义包括声明,当定义变量时,就声明了它的类型和名字。可以通过extern关键字声明变量名字而不定义它。不定义变量的声明包括变量名,变量类型前的关键字extern。
2 函数
1 #include<iostream>
2 using namespace std;
3 int main()
4 {
5 int max(int x, int y); //对max函数作声明
6 int a, b, c;
7 cin>>a>>b;
8 c = max(a,b);
9 cout<<"max="<<c<<endl;
10 return 0;
11 }
12
13 int max(int x, int y)
14 {
15 int z;
16 if(x > y) z = x;
17 else z = y;
18
19 return (z);
20 }
3 类
类的声明只是告诉编译器有这么一个类,它的名字***,它具有哪些成员函数,哪些成员变量。
类的定义是通过实例化类,对其分配存储空间。
1 #include<iostream>
2 using namespace std;
3
4 class Student //声明一个类,类名为Student
5 {
6 private:
7 int num;
8 int score;
9 public:
10 void setdata() //定义公用函数setdata()
11 {
12 cin>>num;
13 cin>>score;
14 }
15
16 void display() //定义公用函数display()
17 {
18 cout<<"num="<<num<<endl;
19 cout<<"score="<<score<<endl;
20 }
21 };
22
23 Student stud1, stud2; //定义stud1与stud2为Student类的变量,成为对象
24
25 int main()
26 {
27 stud1.setdata();
28 stud2.setdata();
29 stud1.display();
30 stud2.display();
31
32 return 0;
33 }