对象数组
每个数组元素都是对象的数组
myclass objs[4]; //构造函数调用四次
要求各个对象的数据成员不同,通过初始值表来赋值数组对象
class exam{
int x;
public:
exam(int n)
{x = n;}
int get_x()
{return x;}
};
main()
{
exam ob[4] = {11,22,33,44};//参数给完第一个对象用逗号隔开继续给后面的
int i;
for (i = 0; i < 4; i++)
{
cout<<ob[i].get_x()<<’’;
cout<<endl;
return 0;
}
}
对象指针
指针往往不会让它只拿一个对象的指针,而是开一组空间
exe *p;
exe ob[2];
p=ob; //等价于p=&ob[0];
p++; //p指向第二个对象 移动的一个对象所占用的存储空间的字节数
this指针
是一个隐含的指针
静态成员
在该类的任何对象创建之前就存在
它不属于任何对象
定义类的哥哥对象所公有的数据
比全局变量更安全
class small_cat{
private:
double weight;
static double total_weight;
static double total_number;
public:
small_cat(double w)
{
weight=w;
total_weight+=w;
total_number++;
}
void display()
{
cout<<”The small_cat weights ”<<weight<<” pounds\n”;
}
static void total_disp()
{
cout<<total_number<<” small_cat total weight ”;
Cout<<total_weight<<” pounds”<<endl;
}
};
double small_cat:total_weight=0; //有类名限定 不要static
double small_cat::total_number=0;:
int main()
{
small_cat w1(1.8),w2(1.5),w3(1.7);
w1.display();
w2.display();
w3.display();
small_cat::total_disp();
return 0;
}
静态成员函数
一般用于访问同一个类中的静态数据成员以维护类中对象共享的数据或全局变量
静态成员函数一般不访问非静态成员,若访问将作为参数
静态成员函数也可以使内联的
静态成员函数没有this指针
友员
有时候需要在类的外部访问类的私有成员,c++提供了友员函数的机制。
友员函数可以是不属于类的一般函数,也可以是另外一个类的成员函数,还可以是整个类
友员声明可以放在共有或私有部分
友员函数可以定义在类内或者类外
class girl{
char *name;
int age;
public:
girl(char *n, int d)
{
name = new char[strlen(n)+1];
strcpy(name,n);
age = d;
}
friend void disp(girl &); //类girl的友员函数disp
~girl()
{delete name;}
};
void disp(girl &x)
{
cout<<”girl\’s name is:”<<x.name<<”,age:”<<x.age<<”\n”;
}
void main()
{
girl g(“chen xingwei”,18);
disp(g);
}