What does #39;amp;#39; do in a C++ declaration?( 是什么意思在 C++ 声明中做什么?)
问题描述
我是一个 C 人,我正在尝试理解一些 C++ 代码.我有以下函数声明:
I am a C guy and I'm trying to understand some C++ code. I have the following function declaration:
int foo(const string &myname) {
cout << "called foo for: " << myname << endl;
return 0;
}
函数签名与等效的 C 有何不同:
How does the function signature differ from the equivalent C:
int foo(const char *myname)
使用 string *myname
和 string &myname
有区别吗?C++ 中的 &
和 C 中的 *
表示指针的区别是什么?
Is there a difference between using string *myname
vs string &myname
? What is the difference between &
in C++ and *
in C to indicate pointers?
同样:
const string &GetMethodName() { ... }
&
在这里做什么?是否有一些网站解释了 &
在 C 和 C++ 中的使用方式不同?
What is the &
doing here? Is there some website that explains how &
is used differently in C vs C++?
推荐答案
&"表示引用而不是指向对象的指针(在您的情况下为常量引用).
The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).
拥有
foo(string const& myname)
结束
foo(string const* myname)
是在前一种情况下,您可以保证 myname 是非空的,因为 C++ 不允许 NULL 引用.由于您是通过引用传递,因此不会复制对象,就像传递指针一样.
is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.
你的第二个例子:
const string &GetMethodName() { ... }
允许您返回对例如成员变量的常量引用.如果您不希望返回副本,并且再次保证返回的值是非空的,这将很有用.例如,以下内容允许您直接进行只读访问:
Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:
class A
{
public:
int bar() const {return someValue;}
//Big, expensive to copy class
}
class B
{
public:
A const& getA() { return mA;}
private:
A mA;
}
void someFunction()
{
B b = B();
//Access A, ability to call const functions on A
//No need to check for null, since reference is guaranteed to be valid.
int value = b.getA().bar();
}
您当然必须小心不要返回无效的引用.编译器会很乐意编译以下内容(取决于您的警告级别以及您对待警告的方式)
You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)
int const& foo()
{
int a;
//This is very bad, returning reference to something on the stack. This will
//crash at runtime.
return a;
}
基本上,您有责任确保返回的引用实际上有效.
Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.
这篇关于'&' 是什么意思在 C++ 声明中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'&' 是什么意思在 C++ 声明中做什么?


基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01