2013-11-01 61 views
2

我有一个Rectangle类和方形类,都具有相同的参数的构造函数(名称,宽度,高度)从基类继承构造函数?

于是我想到了创建一个基类称为形状和定义Shape.h构造和让Rectangle类和Square类继承Shape类的构造函数。

我面临的问题是,我真的不知道如何从Shape类继承构造函数到Rectangle和Square类。

对不起,如果我问一个简单的问题,因为我仍然是新的C++。

Shape.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 
+0

基础的默认构造函数将自动调用。 – billz

+0

我明白了。非常感谢 – user2935569

回答

4

是的,你可以inherit constructors from a base class。这是一个全有或全无的操作,你不能挑选:

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支持它。

+0

VG +1。我认为你应该明确这个暗示定义了'Rectangle :: Rectangle()'。这在Stroustrup的论文中并不清楚,只是在代码评论中。 – EJP

+0

@EJP好点。我补充说,还有一个例子。 – juanchopanza

+0

@juanchopanza非常感谢解释 – user2935569

2

你似乎在问如何调用而不是'继承'它们。答案是用:语法:

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

,其中在每种情况下的参数列表是任何你需要

+0

啊,我明白了。非常感谢 – user2935569

+0

@juanchopanza谢谢。我没有及时了解C++ 11。 – EJP