Cpp_part4

Cpp_part4

Charles Lv7

Cpp_part4

1.单键模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Single {
private:
static Single* self;
Single();

public:
static Single* get_instance();
};
Single* Single::self = NULL;
Single::Single(){};
Single* Single::get_instance() {
if (self == NULL) {
self = new Single();
}
return self;
}

2.reference 引用

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
class Test {
int i;
int* p;

public:
Test(int ai, int am);
Test(const Test& t);
~Test();
};
Test::Test(const Test& t) {
this->i = t.i;
// this->p=t.p[原来系统默认的错误写法]
this->p = new int(*t.p);
}
Test::~Test() {
delete p;
}
Test::Test(int ai, int am) {
i = ai;
p = new int(am);
}
/* int* fun() {
int a = 10;
return &a;
} */

3.const

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
// const与函数返回值的关系
int fun1() {
return 1;
}
// build-in type 内嵌类型
class Test2 {
// const int a;
//老版本编译器会报错,可以用enum代替
public:
const Test2 func();
void fun() const; //此行保证此const变量的此函数可以被调用,只读属性
};
const Test2 Test2::func() {
Test2 t;
return t;
}
/* const int fun2(const int i,const int *p) const{
*p=3;
i++;
}
第一个const 多余,本身自带const
第二个const多余,传值不需要const
第三个需要const,
第四个const表示该函数可以被调用,只读属性*/
void test01() {
Test2 t;
// t.func().func();
//在const存在情况下上面一行会报错
// cout << fun1()++ << endl;
//左值错误,修改常量
}

Summary

pass by value pass by address (pointer ,reference)
功能 read read/write
性能 低效(sizeof(obj)) 高效(sizeof(pointer))
其他 copy constructor nothing
never pass by value

Main part

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
#include <bits/stdc++.h>
using namespace std;
int main() {
Single* s = Single::get_instance();
//拷贝构造(clone):浅拷bitwise copy,深拷贝logical copy
/* 指针五大常见错误
1.野指针(不赋值就写NULL)
2.内存泄漏
3.重复释放
4.返回局部变量地址
5.类似浅拷贝 */
Test t1(1, 2);
Test t2(t1);
// strcpy(); 其中const为只读
/* free标准写法:
if(p!=NULL){
free(p);
p=NULL;
} */
const double pi = 3.14;
test01();
const Test2 t;
t.fun();
return 0;
}
  • Title: Cpp_part4
  • Author: Charles
  • Created at : 2022-12-28 08:25:52
  • Updated at : 2023-02-09 17:57:11
  • Link: https://charles2530.github.io/2022/12/28/cpp-part4/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments