这个C++程序为什么不能编译

来源:百度知道 编辑:UC知道 时间:2024/06/02 04:53:20
#include<iostream>
using namespace std;
class Student
{
public:
Student (int n,string nam,char s)
{
num=n;name=nam;sex=s;
cout<<"Constructor is called"<<endl;
}
~Student (){cout<<"destructing is called !"<<endl;}
void display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
private:
int num;
char name[20];
char sex;
};
int main()
{
Student s1(1001,"wang li",'f');
s1.display();
Student s2(1002,"zhang san",'m');
s2.display();
return 0;

不通过的原因是构造函数参数类型与私有成员定义的类型不匹配
有两种改法,一种改成字符数组,另一种改成字符串变量
1)
class Student
{
public:
Student (int n,char nam[],char s) //构造函数中定义字符数组参数nam[]
{
num=n;
strcpy(name,nam); //字符数组赋值用strcpy();
sex=s;
cout<<"Constructor is called"<<endl;
}
private:
int num;
char name[20]; //私有数据成员为字符数组类型
char sex;
};
2)
#include <string> //字符串变量要加入此头文件
Student (int n,string nam,char s) //构造函数定义字符串变量nam
{
num=n;
name=nam; //字符串变量赋值直接用等号
sex=s;
cout<<"Constructor is called"<<endl;
}
private:
int num;
string name; //私有数据成员为字符串变量
char sex;
};

你是c#程序吧

#include<iostream>
using namespace std;
class Student
{
public:
Student (int n,string nam,char s)