C中部分关键字的作用

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值