C++关于char *类型的一个错误

有关指针的错误使用

错误名称:[Warning] deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

故障代码如下:

#include <iostream>
#include <cstring>
using namespace std;
class Student{
	private:
		char num[20];
		char name[20];
		int age;
	public:
		Student(char * num,char name[], int age) {	//问题出现在这里
			strcpy(this->num, num);
			strcpy(this->name, name);
			this->age = age;
		}
		void show() {
			cout << "num = " << this->num << "	name = " << this->name << "	age = " << this->age << endl;
		}
};

int main(void) {
	Student * student = new Student("0504020101", "张三", 20);
	student->show();
}

原因分析:通过主函数中构造方法,给对象student赋了初值,前两个赋值是字符常量,由构造方法中字符数组接收。 由于传递过去的是常量,无法改变其值,而构造方法中的前两个参数为字符数组变量,接收不变的常量会有警告。整型数据就没有这种情况,整型可以直接用常量赋值,而不用加const

解决方法:在构造方法前两个参数前面加上const关键字。

		Student(const char * num,const char name[], int age) {

运行结果:在这里插入图片描述
编译并成功运行

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值