c++无法将参数 2 从“const char [9]”转换为“char *”

c++无法将参数 2 从const char [9]转换为char *
***原因应该是函数的实参与形参类型不匹配, 字符串在内存中是一个常量字符串数组,因此在函数中的形参也应当加上const关键字才行。

#include "pch.h"
#include <iostream>
#include<cstring>
using namespace std;
class Student {
public:
	Student() {
		this->id = 0;
		this->name = NULL;
	}
	Student(int id, const char *name) {//如果这里不加const,那么将报错无法将参数 2 从“const char [9]”转换为“char *”
		this->id = id;
		int len = strlen(name);
		this->name = new char[len+1];
		strcpy_s(this->name, len + 1, name);
	}
	Student(const Student &another) {
		this->id = another.id;
		int len = strlen(another.name);
		this->name = new char[len + 1];
		strcpy_s(this->name,len+1 ,another.name);
	}
	void printS() {
		cout << this->name<<endl;
	}
	~Student() {
		if (this->name != NULL) {
			delete[]this->name;
			this->name = NULL;
			this->id = 0;
		}
	}
private:
	int id;
	char *name;
};
int main() {
	Student s1(1, "zhagnsan");
	Student s2 = s1;
	s1.printS();
	s2.printS();
	return 0;
}

原因应该是函数的实参与形参类型不匹配, 字符串在内存中是一个常量字符串数组,因此在函数中的形参也应当加上const关键字才行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值