【问题标题】:Fail to convert complicated type to bool?无法将复杂类型转换为布尔值?
【发布时间】:2021-07-29 08:40:24
【问题描述】:

我正在为一个类构建一个方法,如下图

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)))' 从“点”到“布尔”

我不知道如何调试。

【问题讨论】:

  • getSize() 只需要返回len
  • minimal reproducible example 中的哪一行会触发此错误? (我看不到任何接近它的东西——特别是,我在您的代码中看不到* 8。)您为什么期望point 对象可以转换为bool? (通常,通过添加您认为编译器错误的原因来引发错误,可以改进此类问题。)
  • s[c] 的类型为 pointpoint 是真还是假意味着什么?你希望while(s[c])在什么情况下运行循环体,或者退出循环?

标签: c++ class pointers methods types


【解决方案1】:

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 之外的地方使用您的类时,lamguage 会将您的对象隐式转换为 bool

另一种方法是定义方法并调用它。

    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
}

在这种情况下,我更喜欢第一个解决方案(使用转换运算符)。第二种解决方案适用于更复杂的类(如人)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多