2013-03-23 70 views
0

我試圖常量性添加到C++中的變量,通過VC拒絕與Error C2664 : cannot convert MyClass * to const MyClass &編譯。我已經竭盡所能,做搜索,閱讀類似的問題(12),我仍然解決不了。無法轉換MyClass的*爲const MyClass的

我的函數定義爲:

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呢?

+2

,編譯精細的一個是正確的。運行時出現了什麼問題? – 2013-03-23 19:10:19

+0

閱讀關於const_cast <> http://www.cplusplus.com/doc/tutorial/typecasting/ – OldProgrammer 2013-03-23 19:11:36

回答

3

const不是一個問題在這裏,它會自動添加。問題是指針與參考。

至於代碼,你告訴我們而言,以下是正確的:

Merge(*instance); 

如果在運行時不工作,問題是你不向我​​們展示的代碼。

1

可以讓你的方法

void ClassFoo::FuncFoo(MyClass* const instance) 

,這似乎是唯一的出路簽名。在原有的實例是一個指向非const MyClass的。你可以使用const_cast,但是那會是正確的嗎?

1

由於NPE說,該方法Merge(*instance);是正確的,但在這裏可以知道在C++作爲「切片」,你可以谷歌,並嘗試通過experemental方式來檢測它的問題。

的主要問題是,如下所述:

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". 
} 
相關問題