下面通过例子观察有无static关键字时程序的变化:
using namespace std;
class people
{
public:
string name;
int age;
people(string na, int ag) :name(na), age(ag)
{
cout << "构造了对象" << endl;
}
void show()
{
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
}
};
int main()
{
people player1("小米", 13);
people player2("小花", 2);
player1.show();
player2.show();
}
运行结果:
加static关键字时:
using namespace std;
class apex
{
public:
static string name;
static int age;
apex(string na,int ag)
{
cout << "调用了apex(string na,int ag)构造函数" << endl;
}
void show()
{
cout << "我是:" << name <<"今年:"<<age<< endl;
}
};
int apex::age = 8;
string apex::name = "咩咩";
int main()
{
apex p1("姐姐", 23);
apex p2("哥哥", 18);
p1.show();
p2.show();
}
运行结果:
值得一提的是,加了static关键字后的变量不能在类内初始化,会引发报错,只能在类外进行初始化;可以在构造函数内进行赋值操作(进行赋值操作后对象的数据将与最后一个对象的数据保持一致,如例子中的对象p1,p2数据都将是哥哥,18)
static关键字,表示该静态数据成员只能被定义一次,而且是在类外定义,被同类的所有对象共享。简而言之就是被加上static关键字的数据,所有对象都是一样数据,如果定义两次会引发重定义报错!
补充:static函数不能调用非static的数据,只能通过对象名调用(即在函数列表传入对象,再通过对象调用数据),static不初始化会报错(无法解析外部命令)
下面这个例子观察const关键字的作用:
using namespace std;
class people
{
public:
string name;
const int age;
people(string na, int ag) :name(na), age(ag)
{
cout << "构造了对象" << endl;
}
const void show()
{
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
}
};
int main()
{
people player1("小米", 13);
people player2("小花", 2);
player1.show();
player2.show();
}
运行结果:
可以看出,加了const关键字后运行结果不会有什么变化,const关键字的功能在于表示变量不可发生改变,改变const变量将会报错;经验证,非const函数可以调用含const的变量/函数和非const的变量/函数,const函数也可以调用含const的变量/函数和非const的变量/函数。
本文章主要回顾的知识点有:static关键字,const关键字