Maqi extend Human
class Human {
//默认篇protected类型 不能被外部调用 加上public标志后可直接取
public:
int weight;
int height;
public:
//封装性 保护成员安全 与java相同
int getWeight() {
return weight;
}
virtual int getHeight() {
return height;
}
//这个构造函数很先进 可以设置默认参数 类似于Kotiln
public:
Human(int weight, int height) : weight(weight = 100), height(height = 170) {}
Human() : weight(weight = 100), height(height = 170) {}
};
//注意 public很重要 如果不公开后面将无法调用Human类的所有成员以及函数,当然他也可以设置成protected类型
class Maqi : public Human {
public:
string name;
int age;
//这里的&没什么作用 因为加不加都表示name变量
string &getName() {
return this->name;
}
//比较重要 间接调用父类的函数 需要加上 Human::
int getWeight() {
return Human::getWeight()+100;
}
//构造函数传参 类似于java中的super关键字
Maqi(int weight, int height) : Human(weight, height) {
cout << " Maqi()" << endl;
}
//同上 这里不予理会Human的构造
Maqi(string name) : Human() {
this->name = name;
}
//空参构造 和java不同 必须手写
Maqi() : Human() {
cout << " Maqi()" << endl;
}
//析构函数 delete之后释放
virtual ~Maqi() {
cout << name << " ~Maqi()" << endl;
}
//这个函数为拷贝函数 默认会生成一个 不建议重写 如果重写可能会出现奇怪的BUG。
Maqi(Maqi &maqi) : Human() {
age = maqi.age;
name = maqi.name;
}
};
class SuperMan : public Human {
int getHeight() {
return height + 100;
}
};
调用
string *maqi = new string("maqi");
Maqi *maqis = new Maqi(*maqi);
cout << "maqis->getWeight() = " << maqis->getWeight() << endl;
Maqi copyMaqi(*maqis);
cout << "maqis->getWeight() = " << maqis->Human::getWeight() << endl;
cout << "==============================================" << endl;
Maqi changeMqi(copyMaqi);
cout << "maqis->getWeight() = " << maqis->weight << endl;
cout << "==============================================" << endl;
string *change = new string("change");
cout << "maqis->getWeight() = " << maqis->getWeight() << endl;
cout << "====================delete==========================" << endl;
SuperMan superMan;
superMan.weight = 1000;
cout << " superMan.height = " << superMan.height << endl;
cout << " superMan.weight = " << superMan.weight << endl;
Human *human = &superMan;
cout << " human.height = " << human->getHeight() << endl;
cout << " human.weight = " << human->getWeight() << endl;
delete maqis;
//delete changeMqi;
//delete copyMaqi;
总结:
1.maqis->Human::getWeight()为调用父类的函数,比Java麻烦
2.maqis->getWeight()那么就是对父类函数的重写
3. maqis->weight 当Hunam成public之后即可直接调用和java一样。
4.new和delete成对存在,这里之所以注释掉 delete changeMqi; delete copyMaqi;
是因为报“argument given to ‘delete’, expected pointer”
· 5.现在我们新增一个Superman继承Human,使用Human对象接受superman的指针,效果和java是一样的,然而 超人肯定异于常人,需要调用自己的getHeight方法,这时候自用在Human中的getHight前面加上virtual 标志就好了,表明这是一个虚函数,这个和java的抽象函数类似,不过java语言更加严格。