对构造函数的形参:其中使用char型变量和数组时,会出错,对出错类型的总结和解决方法

标题对构造函数的形参:其中使用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 []”
解决办法:
暂时还不知道。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值