函数声明中的const关键字位置

aia*_*iao 7 c++ pointers const

可能重复:
C++中的const声明之间的差异

#include <iostream>

class Bar{};

void foo(const Bar x){}  //l5
void foo(Bar x){}        //l6
void foo(Bar const x){}  //l7

////pointer functions

void foo(const Bar* x){} //l11
void foo(Bar* x){}       //l12
void foo(Bar* const x){} //l13
Run Code Online (Sandbox Code Playgroud)

编译器输出:(长话短说l5,l6,l7冲突;但只l12,l13冲突)

untitled.cpp:6:6: error: redefinition of ‘void foo(Bar)’
untitled.cpp:5:6: error: ‘void foo(Bar)’ previously defined here
untitled.cpp:7:6: error: redefinition of ‘void foo(Bar)’
untitled.cpp:5:6: error: ‘void foo(Bar)’ previously defined here
untitled.cpp:13:6: error: redefinition of ‘void foo(Bar*)’
untitled.cpp:12:6: error: ‘void foo(Bar*)’ previously defined here
Run Code Online (Sandbox Code Playgroud)

怎么了?

  1. 每个声明的含义是什么
  2. 为什么所有3个声明都与对象函数冲突,而只有2个与指针函数冲突?
  3. 请详细说明冲突介于l12和之间l13,即使l12不包含const关键字
  4. 如果琐碎的问题,真的很抱歉

Mar*_*k B 5

"问题"是const参数值的ness不参与重载!

首先,Bar constconst Bar已经是相同的意思,所以他们会自动有问题.但作为函数参数const不适用于重载,因此Bar函数的版本也看起来也一样.将const在paremeter只告诉你不打算修改函数体中的编译器.

出于同样的原因,Bar*并且Bar* const处理相同:const适用于参数的值(不是指向的)并且不参与重载,因此您定义了相同的函数.

另一方面,这const Bar*意味着完全不同的东西:指向const对象(类型Bar)的非const指针.由于类型不同,它确实参与重载并允许该函数是唯一的.