C++ 无法将复杂类型转换为布尔类型?
我正在为一个类构建一个方法,如下所示C++ 无法将复杂类型转换为布尔类型?,c++,class,pointers,methods,types,C++,Class,Pointers,Methods,Types,我正在为一个类构建一个方法,如下所示 const int PointArray::getSize() const { int c=0; while(s[c]) { c++; } const con=c; return con; } 而类的头文件是这样的 class PointArray { point *s; int len; public: PointArray(); virtual ~PointArray(); const int get
const int PointArray::getSize() const
{
int c=0;
while(s[c])
{
c++;
}
const con=c;
return con;
}
而类的头文件是这样的
class PointArray
{
point *s;
int len;
public:
PointArray();
virtual ~PointArray();
const int getSize() const;
};
class point
{
private:
int x,y;
public:
point(int i=0,int j=0){x=i,y=j;};
};
然后它引发了错误:无法将“*((point*)((const PointArray*)this)->PointArray::s)+((sizetype)(((long-long unsigned int)c)*8))”从“point”转换为“bool”
我不知道如何调试。C++正在尝试将您的类Point转换为原始类型bool。它失败了,因为它不知道如何进行
可以定义类中的隐式转换运算符。这将允许C++对类型进行隐式转换(如您在示例中所做的)。
这就是它的样子:class point
{
private:
int x,y;
public:
point(int i=0,int j=0){x=i,y=j;};
operator bool() {
/* your computation */
};
};
现在,当你的C++类在BoOL中使用时,LangGug会将对象转换成BoL隐式
另一种方法是定义方法并调用它 class point
{
private:
int x,y;
public:
point(int i=0,int j=0){x=i,y=j;};
bool asBool() {
/* your computation */
};
};
// this is what will change in if statement
if(s[c].asBool()){
// do something
}
在这种情况下,我更喜欢第一种解决方案(使用转换运算符)。第二种解决方案适用于更复杂的类(如Person)。
getSize()
只需要返回len
。您的代码中哪一行触发了此错误?(我看不到任何类似的情况——特别是,我在代码中没有看到*8
)为什么您希望点
对象可以转换为bool
?(通常,这类问题可以通过添加您认为编译器出错的原因来改进。)s[c]
属于点类型
。点
为真或假意味着什么?在什么情况下,您希望while(s[c])
运行循环体或退出循环?