例9.5.txt

来自「xieyue-C++程序设计 各章中的 程序代码 适合初学者」· 文本 代码 · 共 31 行

TXT
31
字号
例9.5 包含构造函数和析构函数的C++程序。
#include<string>
#include<iostream>
using namespace std;
class Student                                  //声明Student类
{public:
student(int n,string nam,char s )              //定义构造函数
{num=n;
name=nam;
sex=s;
cout<<″Constructor called.″<<endl;       //输出有关信息
}
~Student( )                                 //定义析构函数
{cout<<″Destructor called.″<<endl;}       //输出有关信息
void display( )                             //定义成员函数
{cout<<″num: ″<<num<<endl;
cout<<″name: ″<<name<<endl;
cout<<″sex: ″<<sex<<endl<<endl; }
private:
int num;
char name[10];
char sex;
};

int main( )
{Student stud1(10010,″Wang_li″,′f′);          //建立对象stud1
stud1.display( );                            //输出学生1的数据  
Student stud2(10011,″Zhang_fun″,′m′);        //定义对象stud2
stud2.display( );                            //输出学生2的数据
return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?