C++ 在类中返回struct时出现问题

C++ 在类中返回struct时出现问题,c++,C++,我在尝试用C++返回我的结构时遇到了一个问题,我对该语言还是新手 我有以下代码 头文件 class Rec : public Rect { public: Rec(); struct xRect { int x; int y; }; struct SRect { int position; xRect *mtype; int value; bool

我在尝试用C++返回我的结构时遇到了一个问题,我对该语言还是新手

我有以下代码

头文件

class Rec : public Rect {
public:
    Rec();

    struct xRect
    {
        int x;
        int y;
    };

    struct SRect
    {
        int position;
        xRect *mtype;
        int value;
        bool enable;
    };

    struct xRect ReturnXRect();

};
Cpp文件

struct xRect Rec::ReturnXRect() {

    struct SRect *xrec = xRe::sRect();

    if (xrec)
        return xrec->mtype;

    return nullptr;
}

我得到错误C2556和C2371。有人知道在类中使用struct的正确方法吗?

您应该将类的名称添加到
xRect
。像这样:

//---Header file

class Rec : public Rect {
public:
    Rec();

    struct xRect
    {
        int x;
        int y;
    };

    struct SRect
    {
        int position;
        xRect *mtype;
        int value;
        bool enable;
    };

    xRect ReturnXRect();   //note: you don't to add the struct keyword

};

由于
xRect
是在类的作用域之外定义的(除非它在
ReturnXRect()
之内),您需要添加
Rec::
来通知编译器您要使用的
xRect
的哪个版本。因为可能有其他
xRect
结构版本是在头文件之外定义的


我还修复了
ReturnXRect()
函数的内容,这样它就不会有语法错误。

现在指出了另一个错误C2440,指向
xrec->
nullptr
@carolzinha,我没有注意到我刚才复制粘贴的函数的内容。;))感谢您的注意。您在CPP文件中使用指针有什么原因吗?
//---Cpp file

Rec::xRect Rec::ReturnXRect() {
//^------------------------------------added Rec:: on return type. `struct`
                                        // keyword is unnecessary.

    SRect *pRec = new SRect();  //i'm assuming this is just an example way 
                                //   to creating your SRect object in your 
                                //   example code. you don't need to allocate 
                                //   actually.

    xRect retVal;

    if (pRec){
        retVal = pRec->mtype;
        delete pRec;             //destroy to avoid memory leak.
    }

    return retVal;
}