目录
C++类的组合
-
以另一个类的对象为数据成员
- 构造函数的写法必须采用初始化参数列表的写法
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. 类的组合构造顺序问题:构造顺序只和定义的顺序有关,与初始化参数列表无关,析构顺序相反
-
类中类
- 依旧受权限限制
- 访问方式需要类名限定
#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: };