在 C++ 中通过引用传递指针
本文将演示有关如何在 C++ 中通过引用传递指针的多种方法。
使用&var
表示法通过引用传递对象
通常,引用为 C++ 中的对象定义了一个别名,并且必须在声明过程中对其进行初始化。初始化的引用仍然绑定到给定的对象,它不能被重新绑定到其他对象。对引用的操作会修改绑定的对象本身。因此,它们是将参数传递给函数的常用方法。引用是首选方法,因为使用引用可以避免将对象隐式复制到被调用方函数范围。下一个示例演示了 const
引用 std::vector
对象传递给在元素中搜索给定值的函数。
#include <iostream>#include <vector>using std::cout; using std::vector;
using std::endl; using std::string;
void findInteger(const vector<int> &arr, int k) {
for (auto &i : arr) {
if (i == k) {
cout << "found - " << k << " in the array" << endl;
return;
}
}
cout << "couldn't find - " << k << " in the array" << endl;
}
int main() {
vector<int> vec = { 11, 21, 121, 314, 422, 4, 242};
findInteger(vec, rand() % 100);
return EXIT_SUCCESS;
}
输出:
couldn t find - 83 in the array
使用*&var
表示法通过引用将指针传递给对象
另一方面,我们可以使用*&var
表示法通过引用该函数来传递指针。指针本身就是对象。可以分配或复制它,以将对引用的引用作为函数参数传递给指针。在这种情况下,&
符号是引用符号,而不是用于检索指向对象在内存中位置的指针的地址运算符。注意,应该使用标准指针取消引用运算符*
访问传递的对象的值。下面的示例代码将给定字符串对象的 ASCII 值打印到 cout
流中。
#include <iostream>#include <vector>using std::cout; using std::vector;
using std::endl; using std::string;
void printASCII(string *&str) {
for (auto &i : *str) {
cout << (int)i << ", ";
}
cout << endl;
}
int main() {
auto str = new string("Arbitrary string");
printASCII(str);
return EXIT_SUCCESS;
}
输出:
65, 114, 98, 105, 116, 114, 97, 114, 121, 32, 115, 116, 114, 105, 110, 103,
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。