How to fix: error: invalid conversion from 'const MyClass*' to 'MyClass*'

落花浮王杯 提交于 2019-12-24 02:57:30

问题


I am getting this compile error:

error: invalid conversion from 'const MyClass*' to 'MyClass*'

Here is the code:

std::tr1::shared_ptr<MyClass> myClassA;
const MyClass* myClassB;
myClassA = std::tr1::shared_ptr<MyClass>(myClassB); // error here

I think I understand the error, just don't know how to fix. I need myClassB to be a const so how to convert/copy classB to a shared_ptr?


回答1:


You'll need a shared pointer to a const object:

std::tr1::shared_ptr<const MyClass> myClassA;
                     ^^^^^



回答2:


You can't go from a const MyClass to MyClass.

myClassA = std::tr1::shared_ptr< **const** MyClass>(myClassB);


来源:https://stackoverflow.com/questions/11484737/how-to-fix-error-invalid-conversion-from-const-myclass-to-myclass

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