Cpp_part5

Cpp_part5

Charles Lv7

Cpp_part5

1.operator 重载运算符

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
class Account {
int aid;
char* name;
int balance;


public:
Account(int id, int ab);
void SaveMoney(int money);
Account& operator+(int money);
Account& operator++();
Account operator++(int);
};
Account::Account(int id, int ab) {
this->aid = id;
this->balance = ab;
}
void Account::SaveMoney(int money) {
this->balance += money;
}
Account& Account::operator+(int money) {
this->balance += money;
return *this;
}
Account Account::operator++(int) {
Account a(*this);
this->balance++;
cout << "a++" << endl;
return a;
} //带占位符的为后加加
Account& Account::operator++() {
this->balance++;
cout << "++a" << endl;
return *this;
}
void test01() {
Account a(1001, 100);
a.SaveMoney(100);
a = a + 100;
a++;
++a;
}

2.new vs malloc

分配空间方面无区别,行为有区别,new会调用构造函数,而malloc不会调用构造

new = malloc + construction

delete = destruct + free [注意顺序问题]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Test {
int* p;

public:
Test();
};
Test::Test() {
cout << "construction" << endl;
cout << sizeof(Test) << endl; // 只有构造函数时,sizeof(Test)为1
}
void test02() {
// new vs. malloc
Test t;
Test* p = (Test*)malloc(sizeof(Test));
Test* q = new Test();
}

Main part

1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
int main() {
test01(); // Operator
test02(); // new delete
return 0;
}
  • Title: Cpp_part5
  • Author: Charles
  • Created at : 2022-12-28 08:30:29
  • Updated at : 2023-02-09 17:57:14
  • Link: https://charles2530.github.io/2022/12/28/cpp-part5/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments