代刷网站系统怎么做,手机怎么用wordpress,电商网站是怎么建设的,特种证书查询入口Item32 确定你的public继承关系建模出is-a的关系
public继承的含义#xff1a;
is-a#xff1a;student是一种person#xff0c;person的范围更大在函数传参的过程#xff0c;eta能同时接受person和student两种变量#xff0c;反之不能
class Person {};
class Student…Item32 确定你的public继承关系建模出is-a的关系
public继承的含义
is-astudent是一种personperson的范围更大在函数传参的过程eta能同时接受person和student两种变量反之不能
class Person {};
class Student : public Person {};void eta(const Person p) {}
void study(const Student s) {}int main() {Person p;Student s;eta(p);eta(s);study(s);study(p);return 0;
}/** 报错信息
main.cpp:11:11: error: invalid initialization of reference of type ‘const Student’ from expression of type ‘Person’11 | study(p);| ^
In file included from main.cpp:3:
item_32.h:14:27: note: in passing argument 1 of ‘void study(const Student)’14 | void study(const Student s) {}
*/
通过public继承建模应该慎重思考父类和子类的关系考虑下面两个例子
企鹅是一种鸟但是不会飞建模方式1不太恰当如果方式2不需要区分会飞和不会飞建模2显得多余方式3将编译器能够限制的错误推迟到了运行期同样不恰当方式4不定义这样的方法如果子类觉得有必要在定义有更广的应用范围
// 建模方式1
class Bird {
public:virtual void fly() {}
};
class Penguin : public Bird {};// 建模方式2
class Bird {};
class FlyingBird : public Bird {
public:virtual void fly() {}
};
class Penguin : public Bird {};// 建模方式3
class Bird {
public:virtual void fly() {}
};
class Penguin : public Bird {
public:virtual void fly() { error(); }
};// 建模方式4
class Bird {};
class Penguin : public Bird {}; 如果是正方形继承自长方形可以看出结果不符合预期
class Rectangle {
public:virtual void setHeight(int newHeight);virtual void setWidth(int newWidth);virtual int height() const;virtual int width() const;
};
class Square : public Rectangle {};
void makeBigger(Rectangle r) {int oldHeight r.height();r.setHeight(r.width() 10);assert(r.height() oldHeight);
}Square s;
makeBigger(s); // 结果不符合预期