复制 MyGreatClass 的 const* 实例的正确方法
Proper way to copy a const* instance of MyGreatClass
让我为像我这样的未来白痴改写一下...
为什么这行不通?是因为我忘记取消引用指针了吗?答案是肯定的。忽略这句话的其余部分,它只是必要的,因为 Whosebug 认为我的代码太多而细节不够。我很高兴继续讨论,直到红色警告框消失...哦,就这样了...
struct MyGreatClass
{
};
struct MyEvenBetterClass
{
const MyGreatClass* great;
MyEvenBetterClass(MyGreatClass* grr)
{
great = grr;
}
};
MyGreatClass instanceOfGreatClass;
MyEvenBetterClass instanceOfMyEvenBetterClass(&instanceOfGreatClass);
MyGreatClass changableGreatClass(instanceOfMyEvenBetterClass.great);
//^ ^ this line won't work because the pointer isn't dereferenced...
只需使用 MyGreatClass 的隐式声明的复制构造函数进行复制:
MyGreatClass changableGreatClass(*instanceOfMyEvenBetterClass.great);
// ^ dereference the pointer
让我为像我这样的未来白痴改写一下...
为什么这行不通?是因为我忘记取消引用指针了吗?答案是肯定的。忽略这句话的其余部分,它只是必要的,因为 Whosebug 认为我的代码太多而细节不够。我很高兴继续讨论,直到红色警告框消失...哦,就这样了...
struct MyGreatClass
{
};
struct MyEvenBetterClass
{
const MyGreatClass* great;
MyEvenBetterClass(MyGreatClass* grr)
{
great = grr;
}
};
MyGreatClass instanceOfGreatClass;
MyEvenBetterClass instanceOfMyEvenBetterClass(&instanceOfGreatClass);
MyGreatClass changableGreatClass(instanceOfMyEvenBetterClass.great);
//^ ^ this line won't work because the pointer isn't dereferenced...
只需使用 MyGreatClass 的隐式声明的复制构造函数进行复制:
MyGreatClass changableGreatClass(*instanceOfMyEvenBetterClass.great);
// ^ dereference the pointer