2016-07-15 77 views
1

我對如何處理C++中的繼承感到困惑如何在C++中創建派生類

我想在構造函數上傳遞參數。但是當我創建一個沒有參數的類時,我只能運行這個。

這個小程序:

#include <iostream> 
using namespace std; 

// Base class 

class Shape { 
    protected: 

    int width, height; 

    public: 

    Shape(int w, int h) { 
    width = w; 
    height = h; 
    } 

    void setDimensions(int w, int h) { 
    width = w; 
    height = h; 
    } 

}; 

// New class Rectangle based on Shape class 

class Rectangle: public Shape { 
    public: 

    int getArea() { 
     return (width * height); 
    } 

}; 

當編譯我得到的錯誤:

$ g++ inheritance.cpp -o inheritance -g -std=c++11 
inheritance.cpp:44:13: error: no matching constructor for initialization of 'Rectangle' 
    Rectangle r(3, 4) 
      ^~~~~ 
inheritance.cpp:33:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided 
class Rectangle: public Shape { 
    ^
inheritance.cpp:33:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided 
inheritance.cpp:33:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided 
+1

只需添加這'矩形(INT W,INT H):外形(W,H){};' – DimChtz

+0

@DimChtz你爲什麼回答評論中的問題?這不是這個功能的意義所在。 –

+0

@πάνταῥεῖ你是對的,抱歉 – DimChtz

回答

3

構造不會從Shape繼承。你需要爲Rectangle提供一個構造函數,可以利用這個參數簽名:

Rectangle(int w, int h) : Shape(w,h) { }