类的定义

来源:互联网 发布:latex mac版 编辑:程序博客网 时间:2024/04/29 16:25
// 类的定义.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <iostream>
using namespace std;




class student
{
private://private可以省略,在类的定义中,默认则认为是private
int num;
char name[10];
char sex;
//以上3个数据成员,一般定义为私有,防止外界的直接访问
public:
void set(int n,char *na,char s)//为什么第二个参数用指针,因为strcpy();函数的参数就是2个指针?
{
num=n;
strcpy(name,na);
sex=s;
}


void display()
{
cout<<num<<endl<<name<<endl<<sex<<endl;
}
//定义函数一般定义为公有的,这样外界可以直接访问
};


student a;//a相当于变量,但是在C++中通称为 对象


int _tmain(int argc, _TCHAR* argv[])
{
a.set(100,"chen",'M');
//因为外界不能直接访问私有数据成员,因此一般通过公有函数间接访问数据成员,这里公有函数起到接口的作用
a.display();
system("pause");
return 0;
}

1 0
原创粉丝点击