- #include <iostream>
-
#include <cstring> //在 vc6.0 下 使用#include<string.h>
-
//在 g++ 环境 为 cstring
-
-
using namespace std;
-
class CStudent
-
{
-
public:
-
CStudent();//构造函数 没有返回值
-
CStudent(char *name,int age); //定义一个带参 构造函数
-
~CStudent(); //析构函数,唯一,不能重载
-
CStudent(const CStudent &student);
-
-
friend class CTeacher;
-
-
CStudent &init(char *name,int age); //赋值功能
-
void add(int age); //对静态成员变量操作
-
void output(); //输出类对象的两个数据成员
-
private:
-
char name[20];
-
static int age; //静态成员变量 在类中声明
-
};
-
-
int CStudent::age=0; //在 类外 定义
-
-
CStudent::CStudent() //无参构造函数
-
{
-
strcpy(this->name," ");
-
this->age=0;
-
}
-
-
CStudent::CStudent(char *name,int age) //带参 构造函数实现
-
{
-
strcpy(this->name,name);
-
this->age=age;
-
}
-
-
CStudent::CStudent(const CStudent &student)
-
{
-
strcpy(this->name,student.name);
-
this->age = student.age;
-
}
-
-
CStudent::~CStudent()
-
{
-
cout<<"the object is deconstructing..."<<endl;
-
}
-
-
CStudent &CStudent::init(char *name,int age)
-
{
-
strcpy(this->name,name);
-
this->age=age;
-
return (*this);
-
}
-
void CStudent::add(int age)
-
{
-
CStudent::age += 10;
-
}
-
void CStudent::output()
-
{
-
cout<<this->name<<" "<<this->age<<endl;
-
}
-
-
/*--------------------------------------------------*/
-
class CTeacher
-
{
-
public:
-
CStudent &visit(CStudent &student,char *name,int age);
-
};
-
-
CStudent &CTeacher::visit(CStudent &student,char *name,int age)
-
{
-
strcpy(student.name,name);
-
student.age = age;
-
return student;
-
}
-
/*--------------------------------------------------*/
-
-
int main()
-
{
-
CStudent stu1;
-
CTeacher teacher1;
-
teacher1.visit(stu1,"tom",23);
-
stu1.add(10); //静态成员变量age +10
-
stu1.output(); //23+10=33
-
-
CStudent stu2; //stu1 stu2 共享静态 age
-
stu2.add(15); //33+15=48 共享的成语变量
-
stu2.output(); // stu2 的 name 初始化是 空串
-
-
return 0;
-
}
- ywx@yuweixian:~/yu/c++/shiyan1$ ./student2
-
tom 33
-
10 这里name 初始化为 空串
-
the object is deconstructing...
-
the object is deconstructing...
-
ywx@yuweixian:~/yu/c++/shiyan1$
阅读(663) | 评论(0) | 转发(0) |