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; } void test02() { 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(); test02(); return 0; }
|