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

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

作者: Mr小熊_1da7 | 来源:发表于2019-06-16 18:00 被阅读0次

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

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/kxjdfctx.html