为什么const有时是函数签名的一部分?

时间:2016-07-06 05:43:21

标签: c++

为什么const在应用于结构指针而不是结构时会创建不同的签名?

E.g。

<div class="list-group">
	<a class="list-group-item" href="#picture" data-toggle="tab">Picture</a>
	<a class="list-group-item" href="#home" data-toggle="tab">Profile</a>
</div>

<div id="myTabContent" class="tab-content">
	<div class="tab-pane fade" id="picture">
		<h1>Picture</h1>
	</div>
	<div class="tab-pane fade" id="home">
		<h1>Profile</h1>
	</div>
</div>

(在gcc版本4.9.2上测试)

更具体地说,当带指针的对不是错误时,为什么底部错误是错误的。引用的重复问题(Functions with const arguments and Overloading)似乎也认为指针的情况应该是重复的。

1 个答案:

答案 0 :(得分:1)

void foo(const test t){
   return;
}

是一个错误,因为它与:

相同
void foo(test t){
   return;
}

这使它成为前一个函数的副本。

当函数的参数为​​test*时,您可以取消引用指针并对其进行修改。修改将在调用函数中可见。

void foo(test *ptr){
   ptr->foo = 10;    // The state of the object in the calling function
                     // is changed.
   return;
}

当函数的参数为​​const test*时,您可以取消引用指针以访问它,但不能修改它。

void foo(const test *ptr){
   std::cout << ptr->foo << std::endl;  // OK
   ptr->foo = 10;                       // Not OK
   return;
}

出于同样的原因,你可以重载:

void foo(test& t);
void foo(const test& t);

当你试图超载

void foo(test t);
void foo(const test t);

当你打电话时,两者都是同样出色的候选人。编译器无法消除两者之间的歧义。另外,请看one of the answers to the dupe。它引用了C ++标准的一节,说明为什么最后两个是等价的。