编译错误:需要指针而不是对象
Compile Error: Wants Pointer instead of Object
我在制作两个obecjts的数组时遇到以下错误。边缘和盒子。
error: conversion from 'const Edge*' to non-scalar type 'Edge' requested.
我希望返回一个边缘数组。
在此头文件上:
class Box
{
private:
bool playerOwned;
bool computerOwned;
Edge boxEdges[4];
int openEdges;
bool full;
public:
Box();
Box(int x, int y);
void setEdges(Edge boxTop, Edge boxBottom, Edge boxLeft, Edge boxRight);
void addEdgeToBox(Edge edge); //add edge to edgeArray.
void setPlayerOwned(bool point);
Edge getBoxEdges() const {return boxEdges;} ****//Error****
bool getPlayerOwned() const {return playerOwned;}
void setComputerOwned(bool point);
bool getComputerOwned()const {return computerOwned;}
int getOpenEdges() const {return openEdges;}
bool isFull()const {return full;}
};
std::ostream& operator<< (std::ostream& out, Box box);
除了在尝试创建 Box 的非头文件中将"Edge"替换为"Box"之外,我收到相同的错误。
Box box = new Box(x+i,y);
Box box = new Box(x+i,y); //error
这里有一个错误。你应该把它写成:
Box *box = new Box(x+i,y); //ok
这是因为当你使用new
时,你是在分配内存,只有指针可以容纳内存,所以box
必须是指针类型。
同样地
Edge getBoxEdges() const {return boxEdges;} //error
应写为:
const Edge* getBoxEdges() const {return boxEdges;} //ok
这是因为boxEdges
是一个数组,它可以衰减为指向其第一个元素的指针类型,并且由于它是 const 成员函数,boxEdges
会衰减成 const Edge*
。
顺便说一下,在第一种情况下,您使用自动对象而不是指针,如下所示:
Box box(x+i, y); //ok
我建议你将operator<<
的第二个参数设为常量引用:
//std::ostream& operator<< (std::ostream& out, Box box); //don't use this
std::ostream& operator<< (std::ostream& out, Box const & box); //use this
这避免了不必要的复制!
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行