![]() |
#2
lonmaor2010-08-04 11:08
|

//包含构造函数和析构函数的 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 dalled." << 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 的数据
system("pause");
return 0;
}
我是初学者,在照葫芦画瓢,上面程序运行报错,请高师指点一二!#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 dalled." << 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 的数据
system("pause");
return 0;
}
[ 本帖最后由 hmsabc 于 2010-8-4 11:30 编辑 ]