as *_* df 2 c++ reference constants
在写作之前,我的英语不好。所以可能会有很多尴尬的句子。
void Func1(const int* _i) { };
void Func2(const int& _j) { };
void Func3(const int* (&_k)) { };
int main()
{
int iNum = 1;
int* pInt = new int(1);
Func1(pInt); // works;
Func2(iNum); //works
Func3(pInt); // error
}
Run Code Online (Sandbox Code Playgroud)
我使用 Visual Studio,错误消息显示“无法将参数 1 从 'int *' 转换为 'const int *&'”
我知道它无法转换,因为“&”。_i 等于 pInt,因此它可能会更改取消引用。但我用的是const。所以我认为它会起作用,但 const 关键字不起作用。为什么 const 关键字与其他情况不同?例)Func1,Func2
Func1(pInt); // works; int* could convert to const int* implicitly
Func2(iNum); //works; int could be bound to const int&
Func3(pInt); // error;
Run Code Online (Sandbox Code Playgroud)
pInt是 a int*,当传递给Func3需要引用的时const int*,它将被转换为const int*,这是一个临时的,不能绑定到对非 const 的左值引用,如const int* &(对const 的非 const指针的左值引用整数)。
如果改变Func3to的参数类型int* &,则不需要转换,pInt可以直接绑定。或者更改为const int* const &(lvalue-reference to const point to const int) 或const int* &&(rvalue-reference) 可以绑定到临时。
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |