问题描述
我之前没有使用过void *和const_correctness,所以我不理解下面的代码在做什么.我想要的只是将由const对象的成员函数返回的void *转换为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.
我收到以下错误
passing 'const MyClass' as 'this' argument of 'void* MyClass::getArr()' discards qualifiers
这是我遇到的实际程序
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);
}
在这种情况下,只有诸如'print()'之类的方法才知道'getData'返回的数据类型.我不能使用模板,因为用户不知道MyClass是如何实现的.谢谢你.随时提出替代方案.
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.
推荐答案
我认为问题不在于从数组到 void *
的转换,而在于尝试调用 obj.当
obj
被标记为 const
并且 MyClass :: getArr()
不是 const
>成员函数.如果您将该成员函数的定义更改为
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); }
然后,该错误应自行解决.您可能还想做一个const-overload:
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); }
这篇关于将const void *转换为const int *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!