lesson2(补充)关于const成员函数

简介: lesson2(补充)关于const成员函数

前言:

将const修饰的成员函数称之为const成员函数const修饰类成员函数,实际修饰该成员函数 隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。

class Date
{
public:
  Date()
    :_year(2023)
    ,_month(10)
    ,_day(28)
  {}
  void print() const   //const限定this指针,相当于const Date* this
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main()
{
  Date a;
  a.print();
  return 0;
}

思考下面的几个问题:

1. const对象可以调用非const成员函数吗?

class Date
{
public:
  Date()
    :_year(2023)
    ,_month(10)
    ,_day(28)
  {}
  void print1() const   //const限定this指针,相当于const Date* this
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
  void print2()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main()
{
  Date a;
  a.print1();
  const Date b;
  b.print1();
  return 0;
}

编译器甚至都没有给出print2这个函数的选项,答案自然是不能,但为什么不能呢?

我们定义的对象b是const类型,他的成员变量不能做修改,那他的别名的成员变量也不能修改,而我们上述代码中b对象不能调用print2函数是因为print2函数有权限放大,所以不能调用。

2. 非const对象可以调用const成员函数吗?

 

class Date
{
public:
  Date()
    :_year(2023)
    ,_month(10)
    ,_day(28)
  {}
  void print1() const   //const限定this指针,相当于const Date* this
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
  void print2()
  {
    cout << _year << "-" << _month << "-" << _day << endl;
  }
private:
  int _year;
  int _month;
  int _day;
};
int main()
{
  Date a;
  a.print1();
  const Date b;
  b.print1();
  Date c;
  c.print2();
  return 0;
}

 

权限放大不可以,但可以有权限的缩小,c对象成员变量可以修改,也可以不修改,他的别名成员变量不可以修改是合理的。

3. const成员函数内可以调用其它的非const成员函数吗?

4. 非const成员函数内可以调用其它的const成员函数吗?

这里是权限的缩小,是OK的


目录
相关文章
|
30天前
|
编译器 C++
C++初阶--类与对象--const成员和日期类的实现
C++初阶--类与对象--const成员和日期类的实现
|
30天前
lesson2(补充)关于>>运算符和<<运算符重载
lesson2(补充)关于>>运算符和<<运算符重载
18 0
|
30天前
|
存储 编译器 C++
lesson-2C++类与对象(中)(二)
lesson-2C++类与对象(中)(二)
20 0
|
30天前
|
编译器 C++
lesson-2C++类与对象(中)(一)
lesson-2C++类与对象(中)(一)
35 0
|
8月前
|
存储 编译器 C语言
C++:类和对象(中)---默认成员函数---运算符重载---const的含义
C++:类和对象(中)---默认成员函数---运算符重载---const的含义
|
10月前
|
编译器 C++
[C++] 类与对象(中)完整讲述运算符重载示例 -- 日期类(Date) -- const成员1
[C++] 类与对象(中)完整讲述运算符重载示例 -- 日期类(Date) -- const成员1
|
10月前
|
安全 编译器 C++
[C++] 类与对象(中)完整讲述运算符重载示例 -- 日期类(Date) -- const成员2
[C++] 类与对象(中)完整讲述运算符重载示例 -- 日期类(Date) -- const成员2
|
C++
扩展知识点-----C++中this指针的使用方法
扩展知识点-----C++中this指针的使用方法
65 0
|
存储 编译器 C语言
|
编译器 C语言 C++