const与类
- 成员函数带有const之后就不能对类中的成员进行改变
- const对象只能访问const成员函数,非const对象可以访问任何函数,const对象里面的所有成员都不能改变,然而只有const成员函数不会对对象中的成员进行改变,所以const对象为了不改变其成员只能调用const函数
- const成员初始化需要在初始化列表中进行
#include<iostream>
using namespace std;
class const_class
{
public :
int a,b,c,d;
const int e;
const_class (int a,int b,int c,int d,int ee = 10):a(a),b(b),c(c),d(d),e(ee){ //只能在初始化列表中进行初始化
// this->e = 100;
}
int f() const{
return a+b+c+d;
}
int g() {
a = a*2;
return a+b+c+d;
}
};
int main()
{
const const_class cc = {1, 2, 4, 3};
// cc.a = 10; //报错!
cout<<"cc.f() = "<<cc.f()<<endl;
cout<<"e = "<<cc.e<<endl;
// cout<<cc.g()<<endl; //报错!
const_class dd = {2,3,4,5}; // 列表初始化
dd.a = 100;
cout<<"dd.f() = "<<dd.f()<<endl;
cout<<"dd.g() = "<<dd.g()<<endl;
return 0;
}
static与类
- 静态对象和静态的变量一样,声明周期为程序结束,结束之后调用析构函数。
- 一般使用
类名::静态成员
使用静态成员。当然对象.静态成员
也可以 - 静态函数只能访问静态成员或者函数。(为了安全,访问非静态的成员,可能会因为对象不存在而出现问题)
#include<iostream>
using namespace std;
class static_member
{
public:
static int stat_mem;
int xx;
static_member(int xx):xx(xx){}
int f(){
return xx + stat_mem;
}
static int g(){
// return xx + stat_mem; //报错
return stat_mem;
}
};
int static_member::stat_mem = 100;
int main()
{
static_member aa(10);
aa.stat_mem = 200;
cout<<static_member::stat_mem<<endl;
cout<<aa.stat_mem<<endl;
cout<<static_member::g()<<endl;
cout<<aa.f()<<endl;
return 0;
}
- 静态成员的初始化方式不能使用构造函数,因为构造函数会多次初始化这个静态变量。正确的方式是在类外面初始化,就像下面写的
#include<iostream>
using namespace std;
class static_member
{
public:
static int stat_mem;
};
int static_member::stat_mem = 10; //不会报错
int main()
{
// static_member::stat_mem = 10; // 报错
// int static_member::stat_mem = 10; // 还是报错
cout<<static_member::stat_mem<<endl;
return 0;
}
另一种是