1 string func(const string &s) 2 { 3 return s; 4 } 5 int main() 6 { 7 cout << func("ddd"); 8 return 0; 9 }
如果将func形参定义为非const,则字符串常量不能作为实参传入
传递指向指针的引用
1 int *&v1 2 //v1 是一个引用,与指向 int 型对象的指针相关联
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 void print_(vector<int>::iterator it1, vector<int>::iterator it2) 5 { 6 for(vector<int>::iterator it = it1; it != it2; ++it) 7 { 8 cout << *it << ‘ ‘; 9 } 10 cout << endl; 11 } 12 int main() 13 { 14 vector<int> v(10); 15 print_(v.begin(), v.end()); 16 return 0; 17 }
数组形参
1 // three equivalent definitions of printValues 2 void printValues(int*) { /* ... */ } 3 void printValues(int[]) { /* ... */ } 4 void printValues(int[10]) { /* ... */ } //编译器忽略为任何数组形参指定的长度。
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 void print_(int (&a)[10]) //&arr 两边的圆括号是必需的,因为下标操作符具有更高的优先 5 { 6 for(int i = 0; i<10; ++i) 7 cout << a[i] << ‘ ‘; 8 cout << endl; 9 } 10 int main() 11 { 12 int a[10]{0}; 13 print_(a); 14 print_(a); 15 return 0; 16 }
//把a大小改为11时,不能通过编译
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 void print_(int (*a)[10])// void print_(int a[][10]), 5 { 6 for(int i = 0; i<2; ++i) 7 for(int j = 0; j<10; ++j) 8 cout << a[i][j] <<endl; 9 } 10 int main() 11 { 12 int a[10][10]={}; 13 a[0][7] = 32; 14 print_(a); 15 return 0; 16 }
可以通过传递指向数组第一个和最后一个元素的下一个位置的指针来传参
1 // const int ia[] is equivalent to const int* ia 2 // size is passed explicitly and used to control access to elements of ia 3 #include <iostream> 4 using namespace std; 5 void printValues(const int ia[], size_t size) 6 { 7 for (size_t i = 0; i != size; ++i) { 8 cout << ia[i] << endl; 9 } 10 } 11 int main() 12 { 13 int j[] = { 0, 1 }; // int array of size 2 14 printValues(j, sizeof(j)/sizeof(*j)); 15 return 0; 16 }
1 // const int ia[] is equivalent to const int* ia 2 // size is passed explicitly and used to control access to elements of ia 3 #include <iostream> 4 using namespace std; 5 int main(int argc, char *argv[]) 6 { 7 for(int i=0; i<argc; ++i)//argc表示字符串个数 8 cout << argv[i] << endl; 9 return 0; 10 }
1 #include <iostream> 2 #include <cstdlib> 3 using namespace std; 4 int main(int argc, char *argv[]) 5 { 6 cout << atoi(argv[1]) + atoi(argv[2]) <<endl; 7 return 0; 8 }
原文:https://www.cnblogs.com/2020R/p/13173316.html