当const遇到重载

成员函数只有const属性不同可以重载

// test.cpp : Defines the entry point for the console application.
//

// #include "stdafx.h"

class Bird
{
public:
   double speed() { return _speed; };
   double speed() const { return _speed; };
   double speed(int age) { return _speed; };
   double speed(int age, int sex) { return _speed; };
private:
   double _speed = 0;
};

int main()
{
   Bird b;
   b.speed();
   int age = 1;
   b.speed(age);
   b.speed(age, 1);
   const Bird bb;
   bb.speed();
   return 0;
}


重载编译器做了哪些事

c++本质上与c一样不能重载,只是在编译器处理后相同函数名的函数变成了“不同”的函数,看一下生成的map文件:

Line 96:  0002:00001560       ?speed@Bird@@QAENH@Z       00412560 f i ConsoleApplication2.obj
	Line 135:  0002:00002820       ?speed@Bird@@QAENHH@Z      00413820 f i ConsoleApplication2.obj
	Line 141:  0002:00003280       ?speed@Bird@@QAENXZ        00414280 f i ConsoleApplication2.obj
	Line 227:  0002:00003a30       ?speed@Bird@@QBENXZ        00414a30 f i ConsoleApplication2.obj

const成员函数重载的处理

// test.cpp : Defines the entry point for the console application.
//

// #include "stdafx.h"
#include <stdio.h>

class Bird
{
public:
   double speed() { 
      return static_cast<const Bird&>(*this).speed();
      //return _speed; 
   };
   double speed() const { return _speed; };
   double speed(int age) { return _speed; };
   double speed(int age, int sex) { return _speed; };
private:
   double _speed = 5;
};

int main()
{
   Bird b;
   printf("%f\n", b.speed());
   int age = 1;
   b.speed(age);
   b.speed(age, 1);
   const Bird bb;
   bb.speed();
   return 0;
}

为什么要存在这两个版本的函数

  1. 对于const成员函数来说,如果只是一个类的使用者,则使用起来更加“放心”,因为此成员函数不会造成“副作用”(改变成员变量)
  2. const成员函数的存在使操作const对象成为可能,这在const &类型的参数传递时是个好消息。

猜你喜欢

转载自blog.csdn.net/iceboy314159/article/details/100824172