在类中返回结构时出现问题

Problem when returning struct within the class

本文关键字:问题 结构 返回      更新时间:2023-10-16

我在尝试返回结构时遇到问题,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。 有人在课堂上有什么正确的工作方式结构?

您应该将类的名称添加到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
};

//---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;
}

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

。我还修复了ReturnXRect()函数的内容,因此它不会出现语法错误。