c++ - 在 C++ 中的多态性中使用初始化列表会造成混淆,因为使用类代替变量
问题描述
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
在这个例子中,我无法理解
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
和
Triangle( int a = 0, int b = 0):Shape(a, b) { }
我知道这类似于 C++ 中 Initializer List 的语法,但是使用 Initializer List 我们可以初始化任何变量,例如
class_apple (int var) : x(var) {}
所以这里x = var,但在上面的代码中代替变量
:Shape(a, b)
使用 Shape 类?这实现了什么,对多态性意味着什么?
解决方案
Rectangle( int a = 0, int b = 0) : Shape(a, b) { }
矩形是一derived
类Shape
。:Shape(a,b)
将 Rectangle 构造函数接收的参数a
和传递b
给它的基类。创建Rectangle
实例时,它使用构造函数为和Shape(int a, int b)
赋值。width
height
也是如此,Triangle
因为它也源自Shape
.
现在考虑以下层次结构。
struct Base {
int x,y;
Base(int a, int b) : x(a), y(b) {}
};
struct Derived : Base {
int m;
Derived(int a, int b, int c) : Base(a, b), m(c) {}
};
在上面的示例中,Derived
类将参数a
和基类构造函数传递b
给基类构造函数,同时使用成员初始化列表m
使用 的值进行初始化c
。
推荐阅读
- html - 如何使用 nodeJS 使用 MySql 数据库中的数据创建 html 选择选项
- python - 如何从对每个 API 查询的结果有限制的 API 请求的 json 输出中导出“结果的特定部分”到文本文件中
- c# - 从 Asp.net c# 执行部署的 SSIS 包
- sql-server - 处理多维立方体的有效方法
- c# - 如何使用 C# 确定 Visual Studio 版本
- javascript - 清除特定输入字段的跨度文本
- python-3.x - 导入 tensorflow_datasets 时出现错误
- couchbase - Couchbase N1QL ORDER by true 和不存在的字段
- javascript - 如何将第一个 # 替换为 ?在查询字符串中,然后使用 Javascript 转发到服务器?
- wordpress - 使用自定义插件 Hook 删除 Wordpress 用户