JY's Den

想了好久


  • 首页

  • 标签

  • 分类

  • 归档

C++ const

发表于 2015-04-18 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// main.cpp
// Cpp
//
// Created by mac on 2017/4/17.
// Copyright © 2017年 JY. All rights reserved.
//

#include <iostream>

using namespace std;


// 内存申请与释放
//int *arr = new int[10];
//delete []arr;

/*
int *p = new int[100];
if(NULL == P) {
// 申请成功
}
*/

// 调用频繁的函数建议写成内联函数
// 内联条件,逻辑简单,不能是递归函数

int main(int argc, const char * argv[]) {

int b = 10;
const int x = 3;
// x = 5; error

const int *y = &x;
y = &b;
// *y = 100; error

const int *const z = &x;
// z = &b; error
// *z = 100; error

// x 为不可变,所以也不能通过 *y2 来改变指针的值
// int *y2 = &x;

// b 有读写权限,指针为读权限,所以正确,上面的为错误
const int *y2 = &b;



// int x = 3;
// const int &y = x;
//
// x = 10;
// y = 100;

return 0;
}

C++ 引用

发表于 2015-04-17 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

#include <iostream>

using namespace std;

typedef struct {
int x;
int y;
}Coord;


void func(int &a, int &b);

int main(int argc, const char * argv[]) {
// 引用:必须要初始化
// int a = 3;

// 类型 *&指针引用名 = 指针;
// int a = 10;
// int *p = &a;
// int *&q = p;
// *q = 20;
// cout << a << endl;

int a = 10;
int &b = a;
b = 20;
cout << a << endl;
cout << b << endl;

Coord c;
Coord &c1 = c;
c1.x = 20;
c1.y = 30;
cout << c.x << ' ' << c.y << endl;


int a1 = 10;
int a2 = 40;

cout << a1 << ' ' << a2 << endl;
func(a1, a2);
cout << a1 << ' ' << a2 << endl;

return 0;
}


void func(int &a, int &b) {
int c = 0;
c = a;
a = b;
b = c;
}

http://blog.csdn.net/Simba888888/article/category/1464971/4

1…56

JY

52 日志
15 标签
GitHub
© 2019 JY
由 Hexo 强力驱动
|
主题 — NexT.Mist v5.1.4