C++构造函数.

来源:百度知道 编辑:UC知道 时间:2024/06/24 16:27:30
#include<iostream>
using namespace std;
#include<string>
class Student
{
private:
int ID;
char *pName;
double fScore;
public:
void getStudent();
Student(int,char*,double);
~Student();
};

Student::Student(int i,char *pn,double fs)
{
ID=i;
pn=new char[10];
strcpy(pName,"pn");
fScore=fs;
}
Student::~Student()
{
cout<<"this is over.";
if(pName){
delete []pName;
}
}
void Student::getStudent()
{
cout<<ID<<" "<<pName<<" "<<fScore<<" "<<endl;
}
void main()
{
Student ss(2,"lala",56.6f);
ss.getStudent();
}

就如上面的程序一样,
系统没查到错误,可是运行的时候就弹出了错误,请问是程序的问题还是编译器的问题,是不是没安装运行环境?
Silen000 .感谢你的回答,
可是你那里的是
pName=new char[10];
不是pn=new char[10]吗?

明显的错误
构造函数改成:
Student::Student(int i,char *pn,double fs)
{
ID=i;
pName=new char[10];
if(strlen(pn)<10)
{
strcpy(pName,pn);
}
else
{
cout << "error: the name must be less than 10 characters!!" << endl;
}
fScore=fs;
}

要注意strcpy的安全性

没错啊??

pn=new char[10];
strcpy(pName,"pn");

strcpy(pName,pn);

楼上的弟兄,你可以讲讲是为什么吗??