在类中返回结构时出现问题
Problem when returning struct within the class
我在尝试返回结构时遇到问题,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()
函数的内容,因此它不会出现语法错误。
相关文章:
- 如何重构类层次结构以避免菱形问题
- 包含矢量指针的结构的内存释放问题
- 在类中返回结构时出现问题
- 我对数据结构、双向链表有一些问题
- C++模板类中结构的编译器问题
- 我的超类中的模板问题与结构定义
- 修改C++结构的特征成员时出现问题
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- 在C++中循环访问自定义结构列表的小问题
- 在C++中对结构向量进行排序时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 我的堆栈和库存清单程序的结构有什么问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 我应该如何在C++中使用结构体解决输入失败的问题?
- DNS 查询格式标头结构中的小字节序问题
- C++,类结构问题
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题