const/static在C/C++中的作用(简写)
static:
C中:
修饰局部变量:静态变量,存放在静态数据区,改变变量的生命周期,直到程序结束释放;
修饰全局变量:静态变量,存放在静态数据区,改变变量的作用域,其他文件不能通过extern引用;
修饰函数:改变函数的作用域,只能在本文件中被调用;
C++中:
修饰成员变量:多个对象共享同一个静态成员变量,既能通过对象访问,也能通过类名访问;需要在类的外部初始化;
修饰成员函数:只能访问静态成员变量,既能通过对象调用,也能通过类名调用。
#include <iostream>
using namespace std;
class Student
{
private:
int id;
public:
static int count; //静态成员变量
Student(int i)
{
id = i;
count++;
}
static void show()
{
cout << "学生信息" << endl;
//cout << id << endl;
//不能在静态成员函数中访问非静态成员变量
cout << count << endl;
}
};
//静态成员变量必须在类的外部初始化
int Student::count = 0;
int main()
[
//多个对象共享一个静态成员变量
Student s1(1);
Student s2(2);
Student s3(3);
//可以通过类名来访问静态成员变量
cout << Student::count << endl;
cout << s1.count << endl;
//既能通过对象访问,又能通过类名访问
cout << Student::show << endl;
cout << s1.show << endl;
return 0;
]
const:
C中:
修饰只读变量,不能通过变量名修改,只能通过其他方式修改(比如通过修改地址进行修改)
C++中:
修饰的是常量,存放在符号表中,如果对const修饰的常量取地址(const int a = 1; int *p = &a;),系统会分配内存存放数值;
修饰成员,需要通过对象初始化列表来初始化;
修饰成员函数,常函数,只能访问数据,不能修改数据。
#include <iostream>
using namespace std;
class Date
{
private:
int year;
int mouth;
int day;
public:
Date(int y, int m, int d);
void show();
};
Date::Date(int y, int m, int d)
{
year = y;
mouth = m;
day = d;
}
void Date::show()
{
cout << "出生: " << year << " " << mouth << " " << day << endl;
}
class Student
{
private:
const int id;
Date m_d; //表示学生的生日
public:
Student(int i, int, int, int); //占位参数
void show();
};
//当类对象作为成员变量并且没有提供无参构造函数的时候,需要用对象初始化列表
Student::Student(int i, int y, int m, int d):m_d(y, m, d), id(i)
{
}
//1、当类中的成员变量被const修饰时,需要通过对象初始化列表来对成员变量赋值
//2、当类对象作为成员变量并且没有提供无参构造函数的时候,需要用对象初始化列表
void Student::show()
{
cout << "学生学号是: " << id << endl;
m_d.show();
}
int main()
{
Student s(1, 1999, 1, 6);
s.show();
return 0;
}