定义一个学生类并进行测试
#include <string>
#include <iostream>
using namespace std;
//学生类
class Student {
public:
void setName(string name) {
m_name = name;
}
void setID(int id) {
m_id = id;
}
void showStudent() {
cout << "name:" << m_name << " ID:" << m_id << endl;
}
public:
string m_name;
int m_id;
};
int main() {
Student stu;
stu.setName("Eric");
stu.setID(250);
stu.showStudent();
return 0;
}

定义一个Person类
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private: // 此处,private可缺省
char Name[20]; // 姓名
char Sex; // 性别
int Age; // 年龄
public:
// 以下定义了四个成员函数
void SetData(char na[ ], char s, int a)
{
strcpy(Name, na); // 直接访问Name
Sex=s; // 直接访问Sex
Age=a; // 直接访问Age
}
void GetName( char *na )
{ strcpy(na, Name);
// 拷贝一个副本, 防止被修改
}
char GetSex( )
{ return Sex; }
int GetAge( )
{ return Age; }
}; // 注意:类定义结束处必须有分号
在类外实现成员函数
#include <cstring>
class Person
{
char Name[20]; //姓名
char Sex; //性别
int Age; //年龄
public:
void SetData(char [ ], char , int );
void GetName(char *);
char GetSex( );
int GetAge( );
};
void Person::SetData(char na[ ], char s, int a) // 类体外定义成员函数
{
strcpy(Name, na);
Sex = s;
Age = a;
}
void Person::GetName( char *na ) // 类体外定义成员函数
{ strcpy(na, Name); }
char Person::GetSex( ) // 类体外定义成员函数
{ return Sex; }
int Person::GetAge( ) // 类体外定义成员函数
{ return Age; }
测试Person类
#include "person.h" //包含例10.1或例10.2中的头文件
#include <iostream>
#include <cstring>
using namespace std;
int main( )
{
Person a, *pa;
char name[20];
// 以下通过对象访问成员
a.SetData("Cheng", 'F', 20);
a.GetName(name);
cout << "Name: " << name <<endl;
cout << " Sex: " << a.GetSex( ) << endl;
cout << " Age: " << a.GetAge( ) << endl;
// 以下通过指针访问成员
pa = &a;
pa ->SetData("Zhang", 'M', 18);
pa ->GetName(name);
cout << "Name: " << name <<endl;
cout << " Sex: " << pa->GetSex( ) << endl;
cout << " Age: " << pa->GetAge( ) << endl;
}

网友评论