创建一个类
时间:2014-05-13 06:13:18
收藏:0
阅读:211
c++是一门面向对象的编程语言,而面向对象的基础就是类
使用C++创建一个Student类
class Student//学生类
{
private://私有
//数据成员
char Name[10];//姓名
int Age;//年龄
int No;//学号
public://公有
//成员函数
//输入学生的信息
void InputStudent(char *name, int age, int no)
{
strcpy(Name, name);
Age = age;
No = no;
}
//输出学生的信息
void OutputStudent(void)
{
cout<<Name<<" "<<Age<<" "<<No<<endl;
}
};
为了减少类中的代码量可以将成员函数在类中声明,在类外面定义
class Student//学生类
{
public:
//成员函数
void Input(char *name, int age, int no);
void Output(void);
private:
//数据成员
char Name[20];
int Age;
int No;
};
void Student::Input(char *name, int age, int no)
{
strcpy(Name,name);
Age = age;
No = no;
}
void Student::Output(void)
{
cout<<Name<<" "<<Age<<" "<<No<<endl;
}
测试程序
程序的全部代码:方法1
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Student//学生类
{
private://私有
//数据成员
char Name[10];//姓名
int Age;//年龄
int No;//学号
public://公有
//成员函数
//输入学生的信息
void InputStudent(char *name, int age, int no)
{
strcpy(Name, name);
Age = age;
No = no;
}
//输出学生的信息
void OutputStudent(void)
{
cout<<Name<<" "<<Age<<" "<<No<<endl;
}
};
int main()
{
//定义两个学生结构
Student stu1, stu2;
//对学生结构赋值
stu1.InputStudent("小明", 10, 1);
stu2.InputStudent("小华", 10, 2);
//输出学生信息
stu1.OutputStudent();
stu2.OutputStudent();
system("pause");
}
程序代码:将成员函数在类外面定义
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Student//学生类
{
public:
//成员函数
void Input(char *name, int age, int no);
void Output(void);
private:
//数据成员
char Name[20];
int Age;
int No;
};
void Student::Input(char *name, int age, int no)
{
strcpy(Name,name);
Age = age;
No = no;
}
void Student::Output(void)
{
cout<<Name<<" "<<Age<<" "<<No<<endl;
}
void main()
{
Student stu1, stu2;
stu1.Input("小明", 10, 1);
stu2.Input("小华", 10, 2);
stu1.Output();
stu2.Output();
system("pause");
}执行结果:
评论(0)