c++中const导致的异常错误

错误1:char *name="小红";//报错,过不了编译,
             //原因:对于vs这种严格的编译器来说。name是自由指针,"小红"是常量
             正确写的方式应该加一个const,具体如下:

const char* name="小红";

错误2:相对隐藏较深的情况,编译不会报错,运行会出错。当我们重载运算符时,容易出错
        创建一个学生类student.h中如下:

#pragma once
#include<string>
#include<iostream>
using namespace std;
class Student
{
public:
	Student(int age = 0, const char* sex=NULL, string id = "00000");
	~Student();
	void description();
	int operator[](string index) const;
	int operator[](int index) ;
private:
	int age;
	char* sex;
	std::string id;//学号
};


student.cpp中如下:

#include "Student.h"
#include<sstream>
#include <iostream>

Student::Student(int age, const char* sex, string id)
{
	this->age = age;
	
	this->id = id;
	if (!sex)
	{
		sex = "未命名";
	}
	this->sex = new char[strlen(sex) + 1];
	strcpy_s(this->sex, strlen(sex) + 1, sex);
}

Student::~Student()
{
	if (sex)
	{
		delete sex;
	}
}

void Student::description()
{
	stringstream ret;
	ret << "年龄:" << age << "\t\t性别:" << sex << "\t\t学号:" << id;
	cout << ret.str() << endl;
}

int Student::operator[](string index) const
{
	if (index == "age")
	{
		return age;
	}
}

int Student::operator[](int index) 
{
	if (index == 0)
	{
		return age;
	}
}




main.cpp中代码如下:

#include <iostream>
#include"Student.h"

int main(void) {


	const Student s1(22,"男", "00001");
	cout << s1[0] << endl;//编译不会报错,运行会报错。
	system("pause");
	return 0;
}

        编译找不到问题,运行会报错!
const对象只能调用const方法,在主函数中我们新建一个常量对象,输出时调用了s1[0],其中0为int数据,只能调用const方法,调用到如下函数去了,参数为0(int类型)传到string里,会报错。
经验:我们在定义方法的时候,如果这个方法不会改变里边的数据(就是说我们不需要改变里边的数据),我们加一个const没有什么坏处。加入const后,此时常量对象和普通对象都可以调用。不加const的话,常量对象没法调用。在声明和定义都加上const


就能正常运行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值