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

2019-06-16  本文已影响0人  Mr小熊_1da7

0 上代码

#include <stdio.h>

#include <string.h>

#include <iostream>

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()"<<endl;

}

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 = "<<this->name<<" ,age = "<<this->age<<")"<<endl;

}

};

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的父类。

上一篇下一篇

猜你喜欢

热点阅读