C++中类的组合

这篇博客探讨了C++中类的构造顺序、默认构造函数、拷贝构造函数和赋值运算符的使用,以及如何在类中定义类。示例展示了构造函数的初始化列表,类的组合构造,以及类内类的实现,包括链表节点的定义和迭代器的模拟。
摘要由CSDN通过智能技术生成

一另一个类的对象为数据成员

         构造函数的写法必须采用初始化参数列表的写法

#include <iostream>
using namespace std;
class student
{
public:
	student() = default;
	student(string name, int age) :name(name), age(age) {}
	void printsdata()
	{
		cout << name << endl << age;
	}
protected:
	string name;
	int age;
};

class teacher
{
public:
	teacher(string sname, int sage, string tname) :A(sname, sage),tname(tname) 
	{//初始化参数列表的写法
		this->tname = tname;
	}
	void printtdata()
	{
		A.printsdata();//不可调用student中的保护类型的函数
	}
protected:
	string tname;
	student A;//只能构造无参对象
};

int main()
{
	teacher A("studentA", 18, "teacherA");
	A.printtdata();
	return 0;
}

         类的组合构造顺序问题

class A
{
public:
	A(string str) :str(str)
	{
		cout << str << endl;
	}
	string str;
};
class B
{
public:
	B(string str) :str(str)
	{
		cout << str << endl;
	}
	string str;
};
class C
{
public:
	C(string str) :str(str)
	{
		cout << str << endl;
	}
	string str;
};
class D
{
public:
	D(string Astr, string Bstr, string Cstr) :a(Astr), b(Bstr), c(Cstr)
	{//初始化参数列表参数顺序,和构造顺序无关无关!!
		cout << "D" << endl;
	}
protected:
	A a;   //定义顺序和构造顺序有关
	B b;
	C c;
};
int main()
{
	D d("A", "B", "C");//构造顺序和初始化参数列表没有任何关系,只和定义顺序有关
	return 0;
}

类中类 (定义在另一个类中的类)

struct Node
{
	int data;
	Node* next;
	Node()
	{
		this->next = nullptr;
	}
	Node(int data)
	{
		this->next = nullptr;
		this->data = data;
	}

};


class List
{
public:
	List()
	{
		headNode = new Node;//创建表头
	}
	void push_front(int data)
	{
		Node* newNode = new Node(data);
		newNode->next = headNode->next;
		headNode->next = newNode;
	}
	//迭代器 类模仿指针行为
	class iterator//类种类,受权限定
	{
	public:
		iterator(Node* pMove=nullptr) :pMove(pMove) {}
		bool operator!=(Node* pMove)
		{

		}
		void operator=(Node* A)//重载=运算符
		{
			this->pMove = A;
		}
		bool operator!=(Node* pMove)
		{
			return this->pMove != pMove;
		}
		iterator operator++()
		{
			pMove = pMove->next;
			return iterator(pMove);
		}
		Node*& operator*()
		{
			return pMove;
		}
	protected:
		Node* pMove;
	};
	Node*  begin()
	{
		return headNode->next;
	}
	Node* end()
	{
		return nullptr;
	}
protected:
	Node* headNode;
};
int main()
{
	List::iterator ite;//类种类的访问
	List list;//构建链表
	for (int i = 0; i < 3; i++)//链表的插入
	{
		list.push_front(i);
	}
	//遍历
	List::iterator iter;//先构建一个iterator对象
	for (iter = list.begin(); iter != list.end(); ++iter)//将iter赋值为链表的开始位置
	{
		cout <<(*iter)->data;
	}
	return 0;
}

类中的默认函数(默认构造函数,默认析构函数,默认拷贝构造函数,默认赋值运算)

class A
{
public:
	A() = default;//表示采用默认的构造函数
	~A() = default;//表示采用默认析构函数
	A(A& A) = default;//表示采用默认的拷贝构造函数
	A& operator=(A& A) = default;//表示采用默认的赋值运算
protected:

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值