标题对构造函数的形参:其中使用char型变量和数组时,会出错,对出错类型的总结和解决方法。
例题参考《c++程序设计(第三版)》谭浩强编著,第256页和第250页
p256页,代码:
#include<iostream>
using namespace std;
#include <string>
class 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 << "name: " << name << endl << "sex: " << sex << endl;
}
private:
int num;
char name[10];
char sex;
};
int main()
{
Student stud1(10010, "Wang_li", 'f');
stud1.display();
Student stud2(10011, "Zhang_fang", 'm');
stud2.display();
return 0;
}
注意程序的第7,10,24 行,在编译时,会出现以下错误:
不可指定数组类型“char [10]”,
和
表达式必须是可修改的左值
与结构体变量中的char类型的赋值基本一样(可以参考我之前的博客)。
解决办法:
全部统一成string型变量。
#include<iostream>
using namespace std;
#include <string>
class 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 << "name: " << name << endl << "sex: " << sex << endl;
}
private:
int num;
string name;
char sex;
};
int main()
{
Student stud1(10010, "Wang_li", 'f');
stud1.display();
Student stud2(10011, "Zhang_fang", 'm');
stud2.display();
return 0;
}
这样就可以正常运行程序了。
(虽然我暂时不知道原理是什么)
p250页的程序:
这是在构造函数的形参表中,char型变量前面有int型变量
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n, char s, char nam[]) :num(n), sex(s)
{
strcpy_s(name, nam);
}
private:
int num;
char sex;
char name[20];
};
Student st1(10110, 'm', "Wang_li");
注意程序的最后一行,系统会提示:
“Student::Student(int,char,char [])”: 无法将参数 3 从“const char [8]”转换为“char []”
解决办法:
暂时还不知道。