C++学习第11课,类的继承初体验(面向对象编程)

0 上代码

#include

#include

#include

using namespace std;

class Person{

private:

char *name;

int age;

public:

Person()

{

this->name = NULL;

this->age = 0;

}

Person(char* name, int age = 0):age(age)

{

this->name = new char[strlen(name)+1];

strcpy(this->name, name);

}

~Person()

{

if(this->name)

{

delete this->name;

}

cout<<"~Person()"<

}

void setname(char* name)

{

if(this->name)

{

delete this->name;

}

this->name = new char[strlen(name)+1];

strcpy(this->name, name);

}

void setage(int age)

{

this->age = age;

}

char* getName(void)

{

return this->name;

}

int getAge(void)

{

return this->age;

}

void printInfo(void)

{

cout<<"(name = "<name<<" ,age = "<age<<")"<

}

};

class Student : public Person {

};

int main(int argc, char **argv)

{

Student x;

x.setname("xiaoming");

x.setage(23);

x.printInfo();

return 1;

}

解释:class Student : public Person  类Student继承Person,也可以说类Student是Person的子类或派生类,Person是Student的父类。

你可能感兴趣的:(C++学习第11课,类的继承初体验(面向对象编程))