簡體   English   中英

使用此代碼時,我總是收到錯誤消息。 我正在嘗試在繼承的類中使用構造函數。 C ++

[英]I keep getting an error when I use this code. I'm trying to use constructors in an inherited class. c++

所以,我的問題是我對班級並不了解很多。 因此,我正在嘗試使此構造函數正常工作。 我需要基本構造函數和派生類的構造函數才能在不實現的情況下工作。 我可以在這里定義它,但我無法實現它。 編譯器告訴我,它期待一個大括號。 #ifdef SHAPE.H #endif SHAPE.H #define

#include<string>
using namespace std;
class QuizShape
{
    private:    
        char outer, inner;
        string quizLabel;

    public:
        //Constructor
        QuizShape();
};

class Rectangle : public QuizShape
{
    public:
        int height, width;

        //Getter & setter methods
        int getHeight() const;
        void setHeight(int);
        int getWidth() const;
        void setWidth(int);

        //Constructor for Rectangle
        Rectangle() : QuizShape();
};

class Square : public Rectangle
{
    public:
        //constructors
        Square() : Rectangle (); This area here is where the error comes // IT says it expects a { but I'm not allowed to define the constructor in line.
        Square(int w, int h) : Rectangle (height , width);
}; 

class doubleSquare : public Square
{
//Fill in with constructors 
};

我不明白它給我的錯誤。 我敢肯定,我也不會重新定義它。

需要定義構造函數。 請觀察定義/使用構造函數的方式的變化。

    #include<string>
    using namespace std;
    class QuizShape
    {
        private:    
            char outer, inner;
            string quizLabel;

        public:
            //Constructor
            QuizShape();
    };

    class Rectangle : public QuizShape
    {
        public:
            int height, width;

            //Getter & setter methods
            int getHeight() const;
            void setHeight(int);
            int getWidth() const;
            void setWidth(int);

            //Constructor for Rectangle
            Rectangle() { } 
            Rectangle(int h, int w): height(h), width(w) { }
    };

    class Square : public Rectangle
    {
        public:
            //constructors
          Square() { }  // 
          Square(int w, int h) : Rectangle (h, w) {}
    }; 

    class doubleSquare : public Square
    {
    //Fill in with constructors 
    };

將構造函數的初始值設定項列表移至定義。 例如,對於Square

//declarations
Square();
Square(int w, int h);

//definitions
Square() : Rectangle() {/*body*/}
Square(int w, int h) : Rectangle(w, h) {/*body*/} //assuming you meant w, h

對聲明中帶有初始化程序列表的其他構造函數也要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM