编译错误:需要指针而不是对象
在制作两个对象的数组时,我收到以下错误:Edge 和 Box。
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);
I am getting the following errors when making Arrays of two obecjts.. Edge and Box.
error: conversion from 'const Edge*' to non-scalar type 'Edge' requested.
I am hoping to return an array of Edges.
On this header file:
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);
I get the same error except replace 'Edge' with 'Box' on the following line in a non-header file attempting to create a Box.
Box box = new Box(x+i,y);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有一个错误。你应该这样写:
这是因为当你使用
new
时,你正在分配内存,并且只有指针才能保存内存,所以box
必须是指针类型。类似地,
应该写成:
这是因为boxEdges是一个数组,它可以衰减为指向其第一个元素的指针类型,并且由于它是const成员函数,所以boxEdges将衰减为
const Edge*
。顺便说一句,在第一种情况下,您可以使用自动对象,而不是第一种情况下的指针:
我建议您将运算符<<的第二个参数设置为常量引用:
这避免了不必要的复制!
One error is right here. You should write this as:
It is because when you use
new
, you're allocating memory, and only a pointer can hold a memory, sobox
has to be pointer type.Similarly,
should be written as:
It is because
boxEdges
is an array, which can decay into pointer type to its first element, and since it is const member function,boxEdges
will decay intoconst Edge*
.By the way, instead of pointer in the first case, you use automatic object as:
I would suggest you to make the second parameter of
operator<<
a const reference:This avoids unnecessary copy!