1.类对象在另一个类里做成员
class Date
{
int year;
int month;
};
class Student{
string name;
Date t;
};
2.类对象在结构体中做成员
类对象可以在结构体中做成员。不过类的对象不能在联合体中做成员。
class Date
{
int year;
int month;
};
struct Student{
string name;
Date t;
};
注意,类成员默认是private的,结构体成员默认是public的
3.报错:cannot declare field “” to be of abstract type""
报错原因:把c++抽象类(含纯虚函数的类叫抽象类)当做成员对象,因为抽象类不可实例化,解决方法把实例对象改成指针
错误:
class Date
{
int year;
int month;
virtual bool parse() = 0;
};
class Student{
string name;
Date t;
};
正确:
class Date
{
int year;
int month;
virtual bool parse() = 0;
};
class Student{
string name;
Date *t;
};
本文介绍了如何在C++中将类对象作为其他类或结构体的成员,并讨论了类对象在联合体中的限制。同时,针对尝试使用含有纯虚函数的抽象类作为成员时遇到的编译错误,提出了使用指针作为解决方案。
1166





