赞
踩
额外记住的知识点:
a 对应的 ASC码 97
A 对应的 ASC码 65
#include <iostream> using namespace std; int main() { int oneInt = 1; int &ref = oneInt; // ref是oneInt的引用,ref等价于oneInt const int &refc = oneInt; // 定义常引用 ref = 2; // 修改ref也相当于修改了oneInt和refc; cout << "oneInt=" << oneInt << "," << "ref=" << ref << endl; // 输出oneInt=2,ref=2 cout << "refc=" << refc << endl; // 输出refc=2 ref = 4; // 修改ref也相当于修改了oneInt和refc; cout << "oneInt=" << oneInt << "," << "ref=" << ref << endl; // 输出oneInt=4,ref=4 cout << "refc=" << refc << endl; // 输出refc=4 oneInt = 3; // 修改oneInt也相当于修改了ref和refc cout << "oneInt=" << oneInt << "," << "ref=" << ref << endl; // 输出oneInt=3,ref=3 cout << "refc=" << refc << endl; // 输出refc=3 int &ref2 = ref; // ref2和ref都是oneInt的引用 cout << "ref2=" << ref2 << endl; // 输出ref2=3 // refc = 5; // 错误,不能使用const定义的常引用对所引用的变量进行更改 return 0; }
#include <iostream> using namespace std; void SwapValue(int a, int b) { int tmp; tmp = a; a = b; b = tmp; cout << "在SwapValue()函数中:\t\ta=" << a << ",b=" << b << endl; } void SwapRef(int & a, int & b) { // a、b值互换 int tmp; tmp = a; a = b; b = tmp; cout << "在SwapRef()函数中:\t\ta=" << a << ",b=" << b << endl; } int main() { int a = 10, b = 20; cout << "数据交换前:\t\ta=" << a << ",b=" << b << endl; SwapValue(a, b); cout << "调用SwapValue后::\t\ta=" << a << ",b=" << b << endl; SwapRef(a, b); cout << "调用SwapRef后::\t\ta=" << a << ",b=" << b << endl; return 0; }
简单易懂的规则:
例子:const char * const p = “ABC”;
*号左侧的const修饰所指的数据
*号右侧的const修饰指针
俩侧都有就是全都修饰。相当于全是常量不可变
求数组长度:
#include <iostream>
#include <string>
using namespace std;
int main() {
string citys[] = {"a", "bb", "ccc", "dddd"};
cout << "cityArr: " << sizeof(citys) / sizeof(string) << endl; // 求数组长度
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。