一另一个类的对象为数据成员
构造函数的写法必须采用初始化参数列表的写法
#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:
};