错误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
就能正常运行。