注册 登录
编程论坛 C++教室

谭浩强例9.5运行出错

hmsabc 发布于 2010-08-04 11:00, 518 次点击
程序代码:
//包含构造函数和析构函数的 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;
}
我是初学者,在照葫芦画瓢,上面程序运行报错,请高师指点一二!

[ 本帖最后由 hmsabc 于 2010-8-4 11:30 编辑 ]
2 回复
#2
lonmaor2010-08-04 11:08
程序代码:

//包含构造函数和析构函数的 C++ 程序
#include <string>
#include <iostream>
using namespace std;
class Student                                      //声明类 Student
{
public:
    Student(int n,char* 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;
    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;
}

改为指针传递就ok了。
不知其所以然的人路过。
#3
hmsabc2010-08-04 11:31
回复 2楼 lonmaor
谢谢!
1