首页 > 解决方案 > 在 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 类?这实现了什么,对多态性意味着什么?

标签: c++

解决方案


Rectangle( int a = 0, int b = 0) : Shape(a, b) { }

矩形是一derivedShape:Shape(a,b)将 Rectangle 构造函数接收的参数a和传递b给它的基类。创建Rectangle实例时,它使用构造函数为和Shape(int a, int b)赋值。widthheight

也是如此,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


推荐阅读