C++學習——day07 宏定義、虛析構、操作符重載、STL--list

虛析構

#include<iostream>
using namespace std;
class Person
{
public:
	virtual ~Person()//加virtual後先執行子類析構再執行父類析構 不加只執行父類析構
	{
		cout << "Person析構" << endl;
	}
protected:
private:
};
class Student:public Person
{
public:
	~Student()
	{
		cout << "student析構" << endl;
	}
protected:
private:
};
int main()
{
	Person* p = new Student;
	delete p;//通過父類指針刪除子類對象

	return 0;
}

宏定義

test.h

#pragma once
#define AA() \
	for(int i=1;i<=10;i++)\
		cout<<i<<endl;
// \:和下一行連接    ()可以傳參
#define BB(ClassName) \
	ClassName ClassName##a;
// ##連接符號

#define CC(ThisClass) cout<<"#ThisClass"<<endl;

//宏不替換雙引號字符串內容 ,# 相當於“”

運算符、操作符重載

#include<iostream>
using namespace std;
class Complex
{
public:
	int a;
	int b;
	Complex& operator+ (Complex &c2)
	{
		this->a += c2.a;
		this->b += c2.b;
		return *this;
	}
	Complex& operator= (Complex &c2)
	{
		this->a = c2.a;
		this->b = c2.b;
		return *this;
	}
	Complex(int a,int b)
	{
		this->a = a;
		this->b = b;
	}
	
};
//重載符號要有返回值,繼續和下一個操作符結合
//對象在符號右邊需要在類外重載 (雙目運算符 兩個參數)

ostream& operator<<(ostream &os, Complex &c)
{
	os << "(" << c.a << "," << c.b << ")";
	return os;
}
//重載左++和右++:帶參數 右++ 不需要傳值、 不帶參數左++
int main()
{
	Complex c1(2, 2), c2(3, 3);
	cout << (c1 + c2) << endl;
	Complex c3 = c1;
	cout << c3 <<endl;
	return 0;
}

list

#include<iostream>
#include <list>
#include <algorithm>
using namespace std;
void visit(int a)
{
	cout << a << endl;
}
int main()
{
	list<int>ls;
	ls.push_back(1);
	ls.push_back(2);

	list<int>::iterator it;
	it = ls.begin();
	while (it != ls.end())
	{
		cout << *it << endl;
		it++;
	}
	for_each(ls.begin(), ls.end(), &visit);

	//指定位置插入刪除
	list<int>::iterator it2 = find(ls.begin(), ls.end(), 2);
	//ls.erase(it2);

	ls.insert(it2, 3);
	for_each(ls.begin(), ls.end(), &visit);


	cout << ls.front() << endl;
	cout << ls.back() << endl;
	cout << ls.empty() << endl;



	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章