C++学习——day07 宏定义、虚析构、操作符重载、STL--list

虚析构

#include
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<
// \:和下一行连接    ()可以传参
#define BB(ClassName) \
	ClassName ClassName##a;
// ##连接符号

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

//宏不替换双引号字符串内容 ,# 相当于“”

运算符、操作符重载

#include
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
#include 
#include 
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;
}

你可能感兴趣的:(C++基础)