Casting const void* to const int*

限于喜欢 提交于 2021-02-10 15:54:09

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/4730503/casting-const-void-to-const-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!