7.下面是类Person的定义和实现,编写类Person的派生类Student(包括定义和实现),使整个程序编译通过并输出“LiGang: 12345” 样例输出:LiGang: 12345
#include <iostream>
#include <cstring>
using namespace std;
class Person {
public:
Person(char *n);
~Person();
char * getname();
private:
char *name; //姓名
};
Person::Person(char *n)
{
name = new char [strlen(n)+1];
strcpy(name,n);
}
Person::~Person()
{
delete []name;
}
char * Person::getname()
{
return name;
}
/**********Program**********/
class Student : public Person {
public:
Student(char *n, int no);
int getno();
private:
int no; //学号
};
Student::Student(char *n, int no) : Person(n) {
if (no < 0) {
throw std::invalid_argument("学号必须为非负整数");
}
this->no = no;
}
int Student::getno() {
return no;
}
/********** End **********/
int main()
{
Student li("LiGang", 12345);
cout<<li.getname()<<": "<<li.getno()<<endl;
}