const数据成员和const成员函数

一 const数据成员

  • const 数据成员的初始化方式:
    • 使用类内初始值(C++11 支持)
    • 使用构造函数的初始化列表 (如果同时使用这两种方式,以初始化列表中的值为最终初始化结果)
      注意: 不能在构造函数或其他成员函数内,对 const 成员赋值!
#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
    Student();
    Student(string name, int age, string bloodType);
    void description() const;  // const成员函数内,不能修改任何数据成员
private:

    string name;
    int age;
    const string bloodType;  // const数据成员,要用类内初始值(const string bloodType = "未知";)或者初始化列表进行初始化
};

Student::Student() :bloodType("未知")
{
    name = "无名";
    age = 18;
}
Student::Student(string name, int age, string bloodType): bloodType(bloodType)
{
    this->name = name;
    this->age = age;
}

void Student::description() const
{
    cout << "name:" << name << " age:" << age << " bloodType:" << bloodType << endl;
}


int main()
{
    Student s1;
    Student s2("小红", 17, "B");
    s1.description();
    s2.description();
    return 0;
}

image

二 const成员函数

  • const 成员函数内,不能修改任何数据成员!
    C++的成员函数设置建议: 如果一个对象的成员函数,不会修改任何数据成员,那么就强烈建议: 把这个成员函数,定义为 const 成员函数!

三 常见错误

3.1 const对象,不能调用非const方法

#include <iostream> 
#include <windows.h> 
using namespace std; 
class Man
{ 
public: 
  Man(){} 
  void play() 
  { 
    cout << "I am playing ...." << std::endl;
  }
};

int main(void) 
{ 
  const Man man; 
  //man.play(); //报错:error C2662: “void Man::play(void)”: 不能将“this”指针从“const Man”转换为“Man &”
  return 0;
}

image
解决方案:
方案 1: 把 const Man man; 修改为: Man man;
方案 2: 把 play 方法, 修改为 const 方法

3.2 非 const 引用, 不能对 const 变量进行引用

class Man
{
public:
    Man() {}

    void play() const
    {
        cout << "I am playing ...." << endl;
    }
};

void play(Man& man) 
{ 
    man.play(); 
}

int main(void)
{
    const Man man;
    //play(man);  // error C2664: “void play(Man &)”: 无法将参数 1 从“const Man”转换为“Man &”

    return 0;
}

image

原因: 非 const 引用, 不能对 const 变量进行引用
注意: const 引用, 可以对非 const 变量进行引用
image

解决方案: 修改引用变量, 或者被引用的变量

posted @ 2022-04-29 04:20  荒年、  阅读(74)  评论(0编辑  收藏  举报