示例:
class Person
{
public:
void Print()
{
cout << "name:" << _name << endl;
cout << "age:" << _age << endl;
}
protected:
string _name = "Andy"; // 姓名
int _age = 18; ?// 年龄
};
// 继承后父类Person的成员(成员函数+成员变量)都会变成子类的一部分。
class Student : public Person
{
protected:
int _stuid; // 学号
};
class Teacher : public Person
{
protected:
int _jobid; // 工号
};
定义:Person是父类,也称作基类。Student是子类,也称作派生类。
class Person
{
protected :
string _name; // 姓名
? ?string _sex; ?// 性别
? ? int _age; // 年龄
};
class Student : public Person
{
public :
int _No ; // 学号
};
void Test ()
{
Student sobj ;
// 1.子类对象可以赋值给父类对象/指针/引用
Person pobj = sobj ;
Person* pp = &sobj;
Person& rp = sobj;
? ?
//2.基类对象不能赋值给派生类对象
? ?sobj = pobj;
? ?
? ?// 3.基类的指针可以通过强制类型转换赋值给派生类的指针
? ?pp = &sobj
? ?Student* ps1 = (Student*)pp; // 这种情况转换时可以的。
? ?ps1->_No = 10;
}
class Person
{
public:
Person(const char* name = "Andy")
: _name(name)
{
cout << "Person()" << endl;
}
Person(const Person& p)
: _name(p._name)
{
cout << "Person(const Person& p)" << endl;
}
Person& operator=(const Person & p)
{
cout << "Person operator=(const Person& p)" << endl;
if (this != &p)
_name = p._name;
return *this;
}
~Person()
{
cout << "~Person()" << endl;
}
protected:
string _name; // 姓名
};
class Student : public Person
{
public:
Student(const char* name, int num)
//:_name(name) error
:Person(name) //需要显示调用
,_num(num)
{
cout << "Student()" << endl;
}
//这里调用父类的拷贝构造需要传过去一个父类对象
//那么如何拿到一个父类的对象呢? --- 切片
Student(const Student& s)
:Person(s)
,_num(s._num)
{
cout << "Student(const Student& s)" << endl;
}
Student operator=(const Student& s)
{
if (this != &s)
{
//operator=(s); //这里构成隐藏
Person::operator=(s);
_num = s._num;
}
cout << "Student operator=(const Student& s)" << endl;
return *this;
}
//由于多态的原因,析构函数会被处理成destructor
//destructor(){}
~Student() //
{
//Person::~Person(); //这里构成隐藏
cout << "~Student()" << endl;
}
//注:子类的析构函数完成时,会自动调用父类析构,保障先析构子,在析构父
protected:
int _num; //学号
};
int main()
{
Student s("Andy",18);
//Student s1(s);
//Person p = s;
//s = s1;
return 0;
}
class Student;
class Person
{
public:
friend void Display(const Person& p, const Student& s);
protected:
string _name; // 姓名
};
class Student : public Person
{
protected:
int _stuNum; // 学号
};
void Display(const Person& p, const Student& s)
{
cout << p._name << endl;
cout << s._stuNum << endl;
}
void main()
{
Person p;
Student s;
Display(p, s);
}
class Person
{
public:
Person() { ++_count; }
public:
string _name; // 姓名
public:
static int _count; // 统计人的个数。
};
int Person::_count = 0;
class Student : public Person
{
protected:
int _stuNum; // 学号
};
class Graduate : public Student
{
protected:
string _seminarCourse; // 研究科目
};
int main()
{
Person p1;
Student s1;
cout << &p1._name << endl;
cout << &s1._name << endl;
cout << &p1._count << endl;
cout << &s1._count << endl;
Graduate g1;
Graduate g2;
cout << Person::_count << endl;
cout << Graduate::_count << endl;
//父类静态成员子类共享
return 0;
}
以上仅供参考,欢迎讨论
?