2

コンストラクター (名前、幅、高さ) で同じ引数を持つ Rectangle クラスと Square クラスがあります。

そこで、Shape という Base クラスを作成し、Shape.h にコンストラクターを定義して、Rectangle クラスと Square クラスに Shape クラスからコンストラクターを継承させることを考えました。

私が直面している問題は、コンストラクターを Shape クラスから Rectangle および Square クラスに継承する方法がよくわからないことです。

私はまだC++に慣れていないので、簡単な質問をしている場合はご容赦ください。

シェイプ.h

#include <iostream>
#ifndef Assn2_Shape_h
#define Assn2_Shape_h


class Shape {

public:
 Shape() {
     name = " ";
     width = 0;
     height = 0;
 }

Shape(std::string name, double width, double height);

private:
    std::string name;
    double width,height;
};
#endif

Rectangle.h

#include <iostream>
#ifndef Assn2_Rectangle_h
#define Assn2_Rectangle_h


class Rectangle : public Shape {
//how to inherit the constructor from Shape class?
public:
 Rectangle() {

 }

private:

};
#endif

Square.h

#include <iostream>
#ifndef Assn2_Square_h
#define Assn2_Square_h


class Square: public Shape {
//how to inherit the constructor from Shape class?
public:
   Square() {

    }

private:

};
#endif
4

2 に答える 2

4

はい、基本クラスからコンストラクターを継承できます。これは全か無かの操作であり、選択することはできません。

class Rectangle : public Shape 
{
  //how to inherit the constructor from Shape class?
 public:
  using Shape::Shape;
};

これにより、コンストラクターが派生型であるかのように暗黙的に定義され、次のように構築できますRectangles

// default constructor. No change here w.r.t. no inheriting
Rectangle r; 

// Invokes Shape(string, double, double)
// Default initializes additional Rectangle data members
Rectangle r("foo", 3.14, 2.72); 

これは C++11 の機能であり、コンパイラのサポートは異なる場合があります。GCC と CLANG の最新バージョンはそれをサポートしています。

于 2013-11-01T06:11:31.327 に答える
2

それらを「継承」するのではなく、呼び出す方法を尋ねているようです。答えは : 構文にあります:

Rectangle() : Shape() {
// ...
}

それぞれの場合の引数リストは必要なものです

于 2013-11-01T05:59:16.653 に答える