2016-07-15 64 views
3

以下是代碼之前:模板對象作爲類參數給出錯誤編譯

#include <iostream> 
using namespace std; 

template<class OwnerType> 
class Move { 
public: 
    Move() {} 
    Move(OwnerType &_owner) { 
     owner = &_owner; 
    } 
    void GetPosition() { 
     cout << owner->x << endl; 
    } 
    OwnerType *owner; 
}; 

class Entity { 
public: 
    int x = 50; 
    Move<Entity> *move; 
}; 


int main() {   
    Entity en; 
    en.x = 77; 
    en.move = new Move<Entity>(en); // sign '=' is underlined by VS 
    en.move->GetPosition(); 
    return 0; 
} 

錯誤它給:

a value of type "Move<Entity> *" cannot be assigned to an entity of type "Move<Entity> *" 

的程序編譯,按預期工作,給出的預期值,但錯誤仍然在這裏。 這可能與模板和編譯時間和東西有關,但我沒有足夠的知識來知道這個錯誤實際代表什麼。

也不要擔心泄漏,因爲這只是我測試,錯誤是我不明白。

在此先感謝。

+3

不要相信智能感知。其實編譯。 –

+1

[OT]:您的程序泄漏。 – Jarod42

+0

'int main {'是在你的實際代碼中?錯過了'()'。 –

回答

1

智能感知用於顯示無效錯誤已知的(參見例如Visual Studio 2015: Intellisense errors but solution compiles),信任該編譯器和鏈接,如在意見提出。

但是,這個錯誤很煩人,請嘗試關閉解決方案,刪除.suo文件(它已隱藏),然後再次打開。更多信息在什麼.suo文件在這裏給出Solution User Options (.Suo) File

側面說明,在你的代碼示例main缺少()

+0

是的,這幾乎解釋了一切。謝謝。 –

1

所以它不是錯誤。

它是智能感知: 見:
Error 'a value of type "X *" cannot be assigned to an entity of type "X *"' when using typedef struct

Visual Studio 2015: Intellisense errors but solution compiles


老:

main需求()

這個工作對我來說:

#include<iostream> 
using namespace std; 

template<class T> class Move { 
public: 
    Move() {} 
    Move(T &_owner) { 
     owner = &_owner; 
    } 
    void GetPosition() { 
     cout << owner->x << endl; 
    } 
    T *owner; 
}; 

class Entity { 
public: 
    int x = 50; 
    Move<Entity> *move; 
}; 


int main(){ 
    Entity en; 
    en.x = 77; 
    en.move = new Move<Entity>(en); // sign '=' is underlined by VS 
    en.move->GetPosition(); 

    return 0; 
} 

輸出:

77 
+0

OP說它有效,它是錯誤的無效錯誤 – buld0zzr

+0

它工作正常,但給出了錯誤即使在編譯之前,我也忘記說使用了Visual Studio 2015。 –

+0

智能感知它。感謝幫助。 –

相關問題