-
以另一个类的对象为数据成员
-
构造函数的写法,必须采用初始化参数列表的写法
-
#include<iostream> #include <string> using namespace std; class Hero { public: Hero(string name="", int level=0) :name(name), level(level) {} void print() { cout << name << " " << level << endl; } protected: string name; int level; private: void printData() { cout << "类外无法调用" <<endl; } }; class Heroine { public: Heroine(string name, int level,string mname, int mlevel) :hero(mname, mlevel) { this->name = name; this->level = level; } Heroine(string name, int level) :hero("盖伦",18) { this->name = name; this->level = level; } void print() { hero.print(); //hero.printData();//类外无法调用 cout << name << " " << level << endl; } protected: string name; int level; Hero hero; private: }; int main() { Heroine heroine1("辛德拉", 17,"赵信",16); heroine1.print(); Heroine heroine2("雷欧娜", 17); heroine2.print(); return 0; }
-
-
类的组合构造顺序问题
-
构造顺序只和定义对象顺序的有关,和初始化参数列表无参
-
#include<iostream> #include <string> using namespace std; class A { public: A(string str="") :str(str) { cout << str << " "; } void print() { cout << str << " "; } protected: string str; private: }; class B { public: B(string str="") :str(str) { cout << str << " "; } void print() { cout << str << " "; } protected: string str; private: }; class C { public: C(string str="") :str(str) { cout << str << " "; } void print() { cout << str << " "; } protected: string str; private: }; class D { public: D(string Astr, string Bstr, string Cstr) :a(Astr),b(Bstr),c(Cstr){} void print() { cout << "D" << " "; } protected: C c; A a; B b; private: }; int main() { D d("A", "B", "C"); d.print(); return 0; }
-
-
类中类
-
依旧受权限限定
-
访问方式,需要类名限定
-
#include<iostream> #include <string> using namespace std; struct Node { Node(int data=0) :data(data) { this->next = nullptr; } int data; Node* next; }; class List { public: List() { pList = nullptr; } List(int data) { pList = new Node; if (pList==nullptr) { cout << "内存申请失败" << endl; } pList->data = data; pList = nullptr; } ~List() { delete pList; pList = nullptr; } void insertHead(int data) { if (pList==nullptr) { Node* pNewNode = new Node(data); pList = pNewNode; } else { Node* pNewNode = new Node(data); pNewNode->next = pList; pList = pNewNode; } } //类中类 //迭代器-->类模仿指针行为 class iterator { public: iterator() { pMove = nullptr; } iterator(Node* pMove) :pMove(pMove) { } void operator=(Node* pMove) { this->pMove = pMove; } bool operator!=(Node* pMove) { return this->pMove != pMove; } iterator operator++(int) { pMove = pMove->next; return iterator(pMove); } Node*& operator&() { return pMove; } protected: Node* pMove; private: }; Node* begin() { return pList; } Node* end() { return nullptr; } protected: Node* pList; private: }; int main() { List list; for (int i = 0; i < 5; i++) { list.insertHead(i); } List::iterator iter; for (iter=list.begin();iter!=list.end();iter++) { cout << (&iter)->data << " "; } return 0; }
-