snoobiedoo
snoobiedoo

Reputation: 15

Fail to convert complicated type to bool?

I am building a method for a class, as shown below

const int PointArray::getSize() const
{
int c=0;
while(s[c])
{
    c++;
}
const con=c;
return con;
}

While the header file of the class is like this

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;};
};

then it raised error: could not convert '*(((point *)((const PointArray *)this)->PointArray::s) + ((sizetype)(((long long unsigned int)c) * 8)))' from 'point' to 'bool "

I have no idea of how to debug.

Upvotes: 0

Views: 435

Answers (1)

user14781663
user14781663

Reputation:

C++ is trying to convert your class Point to primitive type bool. It fails because it doesnt know how to do it.

You can define implicit conversion operators in your class. This will allow c++ to do implicit conversion of your type (like you are doing in example).

This is how it would look:

class point
{
private:
    int x,y;

public:
    point(int i=0,int j=0){x=i,y=j;};
    operator bool() {
        /* your computation */
    };
};

Now when you use your class in place where c++ is exceptin bool , lamguage will convert your object to bool implicitly

Another way is to define method and call it.

    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
}

In this case , i would prefer first solution (using conversion operator). Second solutions are for classes that are more complex (like persons).

Upvotes: 1

Related Questions