c++ - 函数重定义:const参数
问题描述
1. 在全球范围内,这给出了error: redefinition of 'f'
#include <iostream>
using namespace std;
void f(int x) { cout << "f" << endl; }
void f(const int x) { cout << "f (const)" << endl; } // error: redefinition of 'f'
int main() { }
2. 定义两个复制构造函数(一个带有const
,另一个不带)编译
#include <iostream>
using namespace std;
class Foo {
public:
Foo(const Foo&) { cout << "copy (const)" << endl; }
Foo(Foo&) { cout << "copy" << endl; }
};
int main() { }
问题
- 为什么 #1 是重定义错误,而 #2 不是?
- 对于第二个示例,是否有定义两个复制构造函数(一个有
const
另一个没有)的用例?
解决方案
两者有本质区别。
一个是 和 之间的过int
载const int
。它是一种价值类型。调用者没有语义差异,效果const
只影响函数体。
void f(int);
int a = 1;
const int b = 2;
f(a); // must copy the int value into the argument
f(b); // same thing.
另一个是 const 与可变引用。它对调用者有所不同。
void f(int&);
void f(const int&);
int a = 1;
const int b = 2;
f(a); // could call f(int&) or f(int const&), but the mutable is a more closely match
f(b); // can only call f(int const&);
由于它是通过引用传递的,因此函数调用者的常量很重要。试图通过引用改变 const 对象的函数必须是无效的,并且默认情况下应将非 const 对象传递给非 const 重载。
只有价值观,这根本不重要。它是一个新对象。无论限定符是什么,它对调用者都没有意义,因此它不应该关心,因为它只影响实现。
您甚至可以仅在需要时在定义中添加 const,因为它声明了相同的函数:
void f(int);
int main() {
f(1);
}
void f(const int a) {
std::cout << "hello " << a << std::endl;
}
至于你的第二个问题,我想说的是,由于添加了右值引用,因此几乎不需要复制构造函数来获取可变引用。
例如,std::auto_ptr
曾经有一个构造函数采用可变引用来转移所有权,但它产生了各种各样的问题。但它已被完全取代std::unique_ptr
,它使用右值引用来转移所有权。
右值引用确保您不关心复制对象的完整性,并且可以从中窃取资源。
推荐阅读
- python - 在独立脚本中使用 Django 模型 - 网站未更新
- xaml - Xamarin bind to another element from within a listview itemtemplate
- c# - asp.net core 中的授权类型
- python - 使用一个小的声音文件来创作一首歌曲
- javascript - Nativescript - 使用 http 模块上传图片
- java - Java从解析的html表中获取数组
- c# - 为什么我的 do While 循环会导致无限循环?
- git - git推送到远程分支问题
- c# - ASP.NET Web 应用程序(.NET 框架)中的 asp.net core SignalR 配置
- android - 在 cognito 中发出 getUser 请求时访问令牌无效