[英]Problem when returning struct within the class
I am having a problem when trying to return my struct in C ++ I am still new to that language.尝试在 C++ 中返回我的结构时遇到问题我仍然是该语言的新手。
I have the following code我有以下代码
Header File头文件
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 file Cpp文件
struct xRect Rec::ReturnXRect() {
struct SRect *xrec = xRe::sRect();
if (xrec)
return xrec->mtype;
return nullptr;
}
I am getting error C2556 and C2371.我收到错误 C2556 和 C2371。 someone what correct way to work struct in the class?
有人在课堂上使用结构的正确方法是什么?
You should add the name of the class to xRect
.您应该将类的名称添加到
xRect
。 like this:像这样:
//---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;
}
since xRect
is defined outside of the scope of the class(unless it's inside ReturnXRect()
you need to add the Rec::
to inform the compiler what version of xRect
you meant to use. since there might be other xRect
version of struct defined outside probably from header files.因为
xRect
是在类的范围之外定义的(除非它在ReturnXRect()
内部, ReturnXRect()
您需要添加Rec::
以通知编译器您打算使用哪个版本的xRect
。因为可能在外部定义了其他xRect
版本的结构可能来自头文件。
I also fixed content of ReturnXRect()
function so it won't have syntax errors.我还修复了
ReturnXRect()
函数的内容,因此它不会有语法错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.