将 const void* 转换为 const int*
我之前没有使用过 void* 和 const_ Correctness 所以我不明白我在下面的代码中做错了什么。我想要的只是将 const 对象的成员函数返回的 void* 转换为 int*。请提出更好的方法。谢谢。
我收到以下错误
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 是如何实现的。谢谢。请随意提出替代方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题不在于从数组到
void *
的转换,而是在obj
时尝试调用obj.getArr()
标记的const
和MyClass::getArr()
不是const
成员函数。如果将该成员函数的定义更改为那么此错误应该会自行解决。您可能还想进行 const 重载:
I think the problem is not in the cast from your array to a
void *
but in trying to callobj.getArr()
whenobj
is markedconst
andMyClass::getArr()
is not aconst
member function. If you change your definition of that member function toThen this error should resolve itself. You might want to do a const-overload as well: