- #include<iostream>
- #include<cstdio>
-
- using namespace std;
- int func(int x)
- {
- x=x+1;
- return x;//如果没有这一行,则输出的z=7,如果有,则z=8
- }
-
- int main()
- {
- int x;
- x=7;
- cout<<"x="<<x<<endl;
- int y=7;
- int z=func(y);
- cout<<"z="<<z<<endl;
- return 0;
- }
上面代码主要用于测试:
1.内外变量
2.外函数是否返回值,返回值有什么区别
3.主函数必须放在程序的最后,因为主函数引用了上面的自定义函数
- #include<iostream>
- #include<cstdio>
-
- using namespace std;
- int f(int& a) { a = a+1; return a; }
- //如果是(int& a)则代表的地址,而不是值
- //如果是int f(int a) { a = a+1; return a; }
- //则传递的数值,下面xx还是0,yy还是7.
- int main()
- {
- int xx = 0;
- cout << f(xx) << endl; // writes 1
- // f() changed the value of xx
- cout << xx << endl; // writes 1
- int yy = 7;
- cout << f(yy) << endl; // writes 8
- // f() changes the value of yy
- cout << yy << endl; // writes 8
-
- }
-
注意上面代码的测试,主要特点在于int f(int& a) { a = a+1; return a; }
&a传递的是地址,下面引用函数的时候,改变的不仅仅是一个数值,而是地址.
- #include<iostream>
- #include<cstdio>
-
- using namespace std;
- int incr1(int a) { return a+1; }
- void incr2(int& a) { ++a; }
-
- int main(){
- int x = 7;
- int y = incr1(x); // pretty obvious
- incr2(x); // pretty obscure
- cout<<y<<endl;
- cout<<x<<endl;
- }
注意两个函数,incr1函数返回了数值,可以用来进行数值传递
而incr2函数并没有返回数值,但是他传递了地址,同样也完成了数值的++;
- #include<iostream>
- #include<cstdio>
-
- using namespace std;
-
- int main(){
- int i = 7;
- int& r = i;//注意地址传递
- r = 9; // i becomes 9
- cout<<i<<endl;
- const int& cr = i;
- // cr = 7; // error: cr refers to const
- i = 8;
- cout << cr << endl; // write out the value of i (that’s 8)
-
- }
注意 int& r=i;类程序的运用,如果修改i的数值,则r也将跟着改变,如果修改r的数值,i的数值也将跟着改变.
但在第二个程序当中,也就是const int& cr = i;不可以修改cr的数值,因为cr所在的内存是一个定量,不可以进行数值修改,但是可以修改i的数值,以此来改变cr定量的数值.
- namespace Jack { // in Jack’s header file
- class Glob{ /*…*/ };
- class Widget{ /*…*/ };
- }
- namespace Jill { // iillill’s header file
- class Glob{ /*…*/ };
- class Widget{ /*…*/ };
- }
-
- #include "jack.h"; // this is in your code
- #include "jill.h"; // so is this
-
- void my_func(Jack::Widget p) // OK, Jack’s Widget class will not
- { // clash with a different Widget
- // …
- }
注意void my_func(Jack::Widget p) Widget.p在上面有两个函数都有这个函数,所以前面必须添加Jack::这样的引用,可以使得程序选定某一个函数,而不是在两个Jack和Jill函数之间进行徘徊,这样会产生错误.
例如:
cout 在名字空间 std中,你可以写成下面的形式:
std::cout << "Please enter stuff… \n“;