4种特殊的数据成员(常量数据成员,引用数据成员,类对象成员,静态成员)
1const数据成员初始化
在构造函数体内或拷贝构造函数体内初始化const数据成员都是非法的
const数据成员只能通过成员初始化表进行初始化
#include <iostream>
#include <stdlib.h>
using namespace std;
class Point
{
private:
const int xPos;
const int yPos;
public:
#if 0 //错误 const数据成员的初始化只能通过成员初始化表
Point(int x,int y)
{
xPos=x;
yPos=y;
}
Point(const Point &pt)
{
xPos=pt.xPos; //构造函数中初始化相当于赋值,而不是初始化
yPos=pt.yPos; //const变量要求必须初始化不能赋值,所以必须在参数列表中
}
#endif
Point(int x,int y):xPos(x),yPos(y)
{
}
Point(const Point &pt)
:xPos(pt.xPos),
yPos(pt.yPos)
{
}
void print()
{
cout<<"xPos"<<xPos<<"yPos"<<yPos<<endl;
}
};
int main()
{
Point pt1(3,4);
pt1.print();
Point pt2(pt1);
pt2.print();
system("pause");
}
2引用初始化 (和const一样必须进行初始化 不能再构造函数体内)
#include <iostream>
using namespace std;
class Point
{
private:
int xPos;
int yPos;
int &ref1;
double &ref2;
public:
Point(int x,int y,double &z)
:ref1(xPos),
ref2(z)
{
xPos=x;
yPos=y;
}
Point(const Point &pt)
:ref1(pt.ref1),
ref2(pt.ref2)
{
xPos=pt.xPos;
yPos=pt.yPos;
}
void print()
{
cout<<"xPos"<<xPos<<",yPos"<<yPos<<endl;
cout<<",ref1:"<<ref1<<",ref2:"<<ref2<<endl;
}
void SetX(int x)
{
xPos=x;
}
};
int main()
{
double outInt=5.0;
Point pt(3,4,outInt);
pt.print();
Point p2(pt);
p2.print();
cout<<"修改p1中的x后"<<endl;
pt.SetX(7);
pt.print();
p2.print();
outInt=6;
cout<<"outInt 变化后"<<endl;
pt.print();
p2.print();
system("pause");
}
3类对象成员的初始化(只能在初始化列表初始)
#include <iostream>
using namespace std;
class point
{
private:
int xPos;
int yPos;
public:
point(int x=0,int y=0)
{
cout<<"点的构造函数被执行"<<endl;
xPos=x;
yPos=y;
}
point(const point &pt)
{
cout<<"点的拷贝构造函数被执行"<<endl;
xPos=pt.xPos;
yPos=pt.yPos;
}
void print()
{
cout<<"("<<xPos<<","<<yPos<<")";
}
};
class line
{
private:
point pt1;
point pt2;
public:
line(int x1,int y1,int x2,int y2)
:pt1(x1,y1),
pt2(x2,y2)
{
cout<<"线的构造函数被执行"<<endl;
}
line(const line &ll)
:pt1(ll.pt1),
pt2(ll.pt2)
{
cout<<"线的拷贝构造函数被执行"<<endl;
}
void draw()
{
pt1.print();
cout<<"to";
pt2.print();
cout<<endl;
}
};
int main()
{
line ll(1,2,3,4);
ll.draw();
line l2(ll);
l2.draw();
system("pause");
}
4static数据成员初始化
静态数据成员的初始化必须在类申明之外进行,且不再包含static关键字
#include <iostream>
#include <stdlib.h>
using namespace std;
class computer
{
private:
float price;
static float total_price;
public:
computer(const float p)
{
price=p;
total_price+=p;
}
~computer()
{
total_price-=price;
}
void print()
{
cout<<"总价是:"<<total_price<<endl;
}
};
float computer::total_price=0;
int main()
{
computer comp1(7000);
cout<<"购买电脑1后"<<endl;
comp1.print();
computer comp2(4999);
cout<<"购买电脑2后"<<endl;
comp2.print();
comp2.~computer();
cout<<"退掉电脑2后"<<endl;
comp2.print();
system("pause");
}
重点注意在初始列表中是初始化,而在构造函数和拷贝构造函数中是赋值不是初始化