【问题标题】:Cannot convert MyClass* to const MyClass无法将 MyClass* 转换为 const MyClass
【发布时间】:2013-03-24 03:45:40
【问题描述】:

我正在尝试为 C++ 中的变量添加常量,但 VC 拒绝使用 Error C2664 : cannot convert MyClass * to const MyClass & 进行编译。我已经尝试了所有方法,完成了搜索,阅读了类似的问题(12),但我仍然无法解决。

我的函数定义为:

void ClassFoo::FuncFoo(MyClass* instance){
     Merge(instance);     // <--- Error C2664 -- cannot convert MyClass* to const MyClass &
     Merge(&instance);     // <--- Error C2664 -- cannot convert MyClass** to const MyClass &
     Merge(*instance);     // <--- This compiles fine, but doesn't work properly at runtime
     Merge(const_cast<const GFxTextFormat&>(instance));     // <--- Error C2440
}

MyClass Merge (const MyClass &instance){
}

我应该怎么做才能正确地将常量添加到变量instance,以便我可以正确调用Merge

【问题讨论】:

标签: c++ visual-c++ syntax constants


【解决方案1】:

const 在这里不是问题,它会自动添加。问题是指针与引用。

就你给我们看的代码而言,以下是正确的:

 Merge(*instance);

如果这在运行时不起作用,则问题出在您没有向我们展示的代码中。

【讨论】:

    【解决方案2】:

    你能在你的方法上签名吗

    void ClassFoo::FuncFoo(MyClass* const instance)
    

    这似乎是唯一的方法。在最初,instance 是指向非常量 MyClass 的指针。你可以使用const_cast,但这对吗?

    【讨论】:

      【解决方案3】:

      正如NPE所说,Merge(*instance);的方法是正确的,但这里可能是c++上称为“slicing”的问题,你可以google它并尝试通过实验方式检测它。

      主要问题如下所述:

      struct A
      { 
        A ( const int value ) : myValue1( value ) {};
      
      private:
        double myValue1;
      };
      
      struct B : public A 
      { 
        B ( const int first, const int second ) : A( first ), myValue2( second ) {};
      
      private:
        double myValue2;
      };
      
      main()
      {
       B child( 1, 2 );  // The "child" object contains two values.
       A parent = child; // Here the "slicing" error, but the compiler will not say anything.
                         // So, the object "parent" now is the new object of type "A" and it memory only one value. 
                         // By the way, it can not be downcasted to object of type "B".
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        相关资源
        最近更新 更多