简体   繁体   English

c ++签名,指针

[英]c++ signatures, pointers

what's the difference between these signatures? 这些签名之间有什么区别?


T * f(T & identifier);
T & f(T & identifier);
T f(T & identifier);

void f(T * identifier); void f(T & identifier); void f(T identifier);

I met pointers in c, but the amperstand in function signature is new for me. 我在c中遇到了指针,但功能签名中的amperstand对我来说是新的。 Can Anyone explain this? 有人可以解释一下吗?

An ampersand in a type declaration indicates a reference type. 类型声明中的&符号表示引用类型。

int i = 4;
int& refi = i;  // reference to i
int* ptri = &i; // pointer to i

refi = 6;  // modifies original 'i', no explicit dereferencing necessary
*ptri = 6; // modifies through the pointer

References have many similarities with pointers, but they're easier to use and less error-prone if address arithmetic is not needed. 引用与指针有许多相似之处,但如果不需要地址算法,它们更容易使用并且更不容易出错。 Also, unlike pointers, references can't be rebound to 'point' to another object after their initialization. 此外,与指针不同,引用在初始化后不能反弹到“指向”另一个对象。 Just ask google for references vs. pointers in C++. 只需要谷歌搜索引用与C ++中的指针。

T * f(T & identifier);
This is a function which takes a reference to T and returns a pointer to T. 这是一个函数,它引用T并返回指向T.的指针。

T & f(T & identifier);
This is a function which takes a reference to T and returns a reference to T. 这是一个函数,它引用T并返回对T的引用。

T f(T & identifier);
This one takes a reference to a T and returns a copy of a T. 这个引用一个T并返回一个T的副本。

void f(T * identifier);
This one takes a pointer to a T and returns nothing. 这个指针指向T并且不返回任何内容。

void f(T & identifier);
This one takes a reference to a T and returns nothing. 这个引用了一个T并且什么也没有返回。

void f(T identifier);
This one takes a T by value (copies) and returns nothing. 这个采用T值(副本)并且不返回任何值。

References behave almost exactly like pointers except a reference is never going to be set to NULL, and a reference is implicitly created and dereferenced for you so you don't need to deal with pointer syntax while calling the function or inside the function. 引用的行为几乎与指针完全相同,只是引用永远不会被设置为NULL,并且隐式创建引用并为其解除引用,因此在调用函数或函数内部时不需要处理指针语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM