简体   繁体   中英

Casting const void* to const int*

I haven't used void* and const_correctness before so I am not understanding what I am doing wrong in the below code. All I want is to cast a void* returned by a member function of a const object to int*. Please suggest better approaches. Thank you.

I get the following error

passing 'const MyClass' as 'this' argument of 'void* MyClass::getArr()' discards qualifiers

So here's the actual program that I had problem with

 class MyClassImpl{
    CvMat* arr;
    public:
        MyClassImpl(){arr = new CvMat[10];}
        CvMat *getArr(){return arr;}
};
class MyClass{
    MyClassImpl *d;
    public:
        const void *getArr()const{ return (void*)d->getArr(); }

};
void print(const MyClass& obj){
    const int* ptr = static_cast<const int *>(obj.getArr());
}
int main(){
    MyClass obj1;
    print(obj1);
}

Only the methods such as 'print()' in this case know the datatype returned by 'getData'. I can't use templates because the user doesn't know how MyClass is implemented. Thank you. Feel free to suggest alternatives.

I think the problem is not in the cast from your array to a void * but in trying to call obj.getArr() when obj is marked const and MyClass::getArr() is not a const member function. If you change your definition of that member function to

 const void *getArr() const { return static_cast<const void*>(arr); }

Then this error should resolve itself. You might want to do a const-overload as well:

 const void *getArr() const { return static_cast<const void*>(arr); }
       void *getArr()       { return static_cast<      void*>(arr); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM