目录
(I)static修饰变量之后成为静态变量,在编译时就会产生空间;
(III)count是大家的,只有一份;name,age,id是私有的,每个成员都有一份
(I)static修饰的成员函数没有this指针(因为this只能用于修饰普通成员,即非静态成员)
(II)static修饰的成员函数只能访问静态成员(变量和函数)
1、C语言
2、c++(拓展)
(1)static修饰成员变量
(I)static修饰变量之后成为静态变量,在编译时就会产生空间;
下列代码运行后会出错,原因:
- static int count:static修饰变量之后会产生空间;
- 整个类是不产生空间的,它只是一个数据类型,在实例化对象的时候才会产生空间
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(string _name="王丹",int _age=15,string _sex="男",int _id=608)
{
name = _name;
age = _age;
sex = _sex;
id = _id;
}
~Student()
{
cout << "析构函数" << endl;
}
void show()
{
cout << name << ",年龄:" << age << ",性别:" << sex << ",学号:" <<id<< endl;
cout << "班级人数:" << count << "人" << endl;
}
private:
string name;
int age;
string sex;
int id;
static int count;//公共变量
};
int main()
{
Student s1;
Student s2("林浩", 65, "男", 609);
s1.show();
s2.show();
return 0;
}
运行结果:
(II)解决思路:
a、目标要求:
在类内不产生空间,在类外产生空间
b、原则:
- static修饰的变量就是在编译时产生空间
- 类内不能产生空间
c、解决方法:
联想到声明不产生空间,定义产生空间
(static修饰的成员变量必须在类内声明,类外定义)
#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
Student(string _name="王丹",int _age=15,string _sex="男",int _id=608)
{
name = _name;
age = _age;
sex = _sex;
id = _id;
}
~Student()
{
cout << "析构函数" << endl;
}
void show()
{
cout << name << ",年龄:" << age << ",性别:" << sex << ",学号:" <<id<< endl;
cout << "班级人数:" << count << "人" << endl;
}
private:
string name;
int age;
string sex;
int id;
static int count;//声明:公共变量(不产生空间)
};
int Student::count = 33;//(1)类外定义:公共变量的值(产生空间)
//(2)类外限制作用域:使得公共变量count还属于类
int main()
{
Student s1;
S