关于引用参数函数调用的一点疑惑。
先来两个例子
void swap (int &a, int &b){ int t = a; a = b; b = t;}//此函数调用a = 5;b = 10;swap(&a,&b); //这里必须取地址做参数,swap里面的参数可以看做引用,也可以看做地址做参数。cout << a ,b <<endl;
String::String(const String &other) { int length = strlen(other.m_data); m_data = new char[length+1]; strcpy(m_data, other.m_data); } string a;a = "abcd";string b(a)// string类的拷贝构造函数,参数依旧是引用// 调用的时候参数还是直接写的实例,难道说参数只是 指向a首地址的指针?
#include <iostream>using namespace std;void swap(int & a, int & b){ cout << "使用引用参数\n"; int temp; temp = a; a = b; b = temp;}void swap(int* a, int* b){ cout << "使用指针参数\n"; int temp; temp = *a; *a = *b; *b = temp;}int main(){ int x = 5; int y = 10; swap(x, y); //引用参数 cout << x << " " << y << endl; swap(&x, &y); //指针参数 cout << x << " " << y << endl; return 0;}