繁体   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