C++类的组合和默认的函数

目录

C++类的组合  

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

类中类

默认函数


C++类的组合  

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

  1. 构造函数的写法必须采用初始化参数列表的写法
class G{
public:
	G(string name,int age){}
protected:
	string name;
	int age;
};
class H{
public:
	H(string str,string name,int age):str(str),g(name,age){}
protected:
	string str;
	G g;//G中的对象承当了H中的数据成员,g对于G也是类外,所以只能访问公有数据
};

   2. 类的组合构造顺序问题:构造顺序只和定义的顺序有关,与初始化参数列表无关,析构顺序相反

  • 类中类

  1.  依旧受权限限制
  2. 访问方式需要类名限定
    #include<iostream>
    #include<string>
    using namespace std;
    struct Node{
    	int data;
    	Node* nextNode;
    	Node(){
    		this->nextNode = nullptr;
    	}
    	Node(int data){
    		this->nextNode = nullptr;
    		this->data = data;
    	}
    };
    class List{
    public:
    	Node* begin(){
    		return headNode->nextNode;
    	}
    	Node* end(){
    		return nullptr;
    	}
    	List(){
    		headNode = new Node;
    	}	
    	void insert(int data){
    		Node* newNode = new Node(data);
    	newNode->nextNode= headNode->nextNode;
    		headNode->nextNode = newNode;
    	}
    	
    	class iterator//迭代器:类模仿指针行为
    	{
    	public:
    		iterator(Node* pMove=nullptr):pMove(pMove){	}
        void operator=(Node* pMove){
    	this->pMove = pMove;
    	}
    	bool operator!=(Node* pMove){
    		return this->pMove != pMove;
    	}
    	iterator operator++(){
    		pMove = pMove->nextNode;
    			return iterator(pMove);
    	}
    	Node operator*(){
    		return *pMove;
    	}	
    	protected:
    	Node* pMove;
    	};
    	
    protected:	
    Node*headNode;
    
    private:
    	
    
    };
    
    int main(){
    
    	List list;
    	for (int i = 0; i < 3; i++){
    
    		list.insert(i);
    	}
    	List::iterator iter;
    	for (iter = list.begin(); iter != list.end(); ++iter){
    		cout << (*iter).data;
    	}
    	while (1);
    	return 0;
    }

默认函数

  • 默认构造函数
  • 默认析构函数
  • 默认拷贝函数
  • 默认赋值运算
    class L{
    public:
    	L() = default;//默认构造函数
    	~L() = default;//默认析构函数
    	L(L& l) = default;//默认拷贝函数
    	L& operator=(L&l) = default;//默认“=”重载
    protected:
    };
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值