2016-07-15 92 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

智能感知它。感谢帮助。 –

相关问题