C++深度解析教程笔记2
- 第3课 - 进化后的 const 分析
- 实验-C与C++的const区别
- 实验-C与C++的const区别&const作用域
- 第4课 - 布尔类型和引用
- 小结
本文学习自狄泰软件学院 唐佐林老师的 C++深度解析教程,图片全部来源于课程PPT,仅用于个人学习记录
第3课 - 进化后的 const 分析
实验-C与C++的const区别
#include <stdio.h>
int main()
{
const int c = 0;
int* p = (int*)&c;
printf("Begin...\n");
*p = 5;
printf("c = %d,*p=%d\n", c,*p);
printf("End...\n");
return 0;
}
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>gcc 31.c
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>a
Begin...
c = 5,*p=5
End...
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>g++ 31.cpp
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>a
Begin...
c = 0,*p=5
End...
实验-C与C++的const区别&const作用域
#include <stdio.h>
void f()
{
#define a 3
const int b = 4;
}
void g()
{
//C++中,宏定义与const区别: define无作用域,const有作用域
printf("a = %d\n", a);//预处理器直接将a替换为3
//printf("b = %d\n", b);
/*
D:\Users\download\BaiDuDownload\test>g++ test.cpp
test.cpp: In function 'void g()':
test.cpp:12:24: error: 'b' was not declared in this scope
printf("b = %d\n", b);
^
*/
}
int main()
{
const int A = 1;
const int B = 2;
int array[A + B] = {0};
int i = 0;
for(i=0; i<(A + B); i++)
{
printf("array[%d] = %d\n", i, array[i]);
}
f();
g();
return 0;
}
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>gcc test.c
test.c: In function 'main':
test.c:19:5: error: variable-sized object may not be initialized
int array[A + B] = {0};
^~~
test.c:19:25: warning: excess elements in array initializer
int array[A + B] = {0};
^
test.c:19:25: note: (near initialization for 'array')
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>g++ test.cpp
D:\Users\download\BaiDuDownload\2 - C++深度解析教程\第1期 — 小试牛刀(免费)\test>a
array[0] = 0
array[1] = 0
array[2] = 0
a = 3
第4课 - 布尔类型和引用
#include <stdio.h>
int main(int argc, char *argv[])
{
bool b = false;
int a = b;
printf("sizeof(b) = %d\n", sizeof(b));
printf("b = %d, a = %d\n", b, a);
b = 3;
a = b;
printf("b = %d, a = %d\n", b, a);
b = -5;
a = b;
printf("b = %d, a = %d\n", b, a);
a = 10;
b = a;
printf("a = %d, b = %d\n", a, b);
a = 0;
b = a;
printf("a = %d, b = %d\n", a, b);
return 0;
}
E:\test>g++ 4-1.cpp
E:\test>a
sizeof(b) = 1
b = 0, a = 0
b = 1, a = 1
b = 1, a = 1
a = 10, b = 1
a = 0, b = 0
E:\test>gcc 4-1.c
4-1.c: In function 'main':
4-1.c:5:5: error: unknown type name 'bool'; did you mean '_Bool'?
bool b = false;
#include <stdio.h>
int main(int argc, char *argv[])
{
int a = 4;
int& b = a;
b = 5;
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("&a = %p\n", &a);
printf("&b = %p\n", &b);
return 0;
}
E:\test>g++ 4-2.cpp
E:\test>a
a = 5
b = 5
&a = 000000000061FE14
&b = 000000000061FE14