c++里面的函数模板问题,意外收获,main函数只能返回int?

it2026-09-27  13

c++ 11标准添加了一项:main函数必须返回int? 以前没有注意这个问题,今天想要换一个环境,使用vscode的时候,发现void main 怎么都不通过,于是上网搜索到了这个答案:原来 The definition void main( ) { / … / } is not and never has been C++, nor has it even been C. 2.使用引用作为形参,可以改变实参的值 以前,为了通过函数改变实参的值,总是使用指针来指向实参的地址,然后改变,今天发现,c++11引入的引用作为函数形参 ,可以改变实参的值 #include <iostream> using namespace std; void fun2(int a, int b, int &c) { c = a + b; } void fun1(int a, int b, int* c) { *c = a + b; } int main() { int a = 0; int &c = a; //引用c与a绑定 c = 4; cout << a << endl; int f; fun2(a, a, f); //通过引用改变实参的值 cout << f << endl; int g; fun1(a, a, &g); //通过指针改变实参的值 cout << g << endl; return 0; } 函数模板 总算抽出时间看函数模板了,总的来说,就是使用template 定义一个可变的参数,使用的时候,指定参数的类型 #include <iostream> using namespace std; template <typename T> void Swap(T a, T b) { T tmp = a; a = b; b = tmp; } template <typename T1, typename T2, typename T3> T1 add(T2 a, T3 b) { T1 ret; ret = static_cast<T1>(a + b); return ret; } int main() { int c = 12; float d = 23.4; //cout << add(c, d) << endl; //error,无法自动推导函数返回值 cout << add<float>(c, d) << endl; //返回值在第一个类型参数中指定 cout << add<int, int, float>(c, d) << endl; //system("pause"); return 0; }

未完待续。。。。。。。。。

最新回复(0)