3.2 定义常量

Posted: March 25, 2011 in C++

Define

/*define是一个过时的定义常量的方法, 但是由于很多程序仍旧使用这种方法编译,所以还有学习的必要,
他的缺点是没有定义类型,因此对于C++的标准,已经被抛弃*/

#include <iostream>

using namespace std;

#define classstudent 60;//可以用来定义数字.
#define name “TONG”;//也可以用来定义string.

int main()
{
               cout<<classstudent;//只要编译器看到classstudent就会自动转换为60.
                cout<<endl;
                cout<<name;
                cout<<endl;
}

Const

/*使用const的优点就是:具有常量类型, 可以使编译器能够根据类型确保它被正确使用.
语法: const+类型+名=值 */

#include <iostream>
#include <string>

using namespace std;

const int classstudent = 15;//一样可以定义数值;
const string name = “TONG”;//也可以定义string.

void main()
{
                cout<<classstudent; 
                cout<<endl;
                cout<<name;
                cout<<endl;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s