【问题标题】:Template object as class parameter gives error before compiling模板对象作为类参数在编译前给出错误
【发布时间】:2016-11-18 11:44:07
【问题描述】:

代码如下:

#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> *"

程序正在编译,按预期工作并给出预期值,但错误仍然存​​在。 这可能与模板和编译时间和其他东西有关,但我没有足够的知识来知道这个错误实际上代表什么。

也不要担心泄漏,因为这只是我测试,错误是我不明白的。

提前致谢。

【问题讨论】:

标签: c++ templates compilation


【解决方案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

【讨论】:

  • OP 说它有效,是无效错误困扰他
  • 它工作正常,但即使在编译之前也会出错,我也忘了说使用了 Visual Studio 2015。
  • 智能感知它是。感谢您的帮助。
【解决方案2】:

Intellisense 以显示无效错误而闻名(参见例如 Visual Studio 2015: Intellisense errors but solution compiles),请相信编译器和链接器,如 cmets 中所建议的那样。

但是,这个错误很烦人,尝试关闭解决方案,删除.suo 文件(它是隐藏的),然后重新打开。有关.suo 文件的更多信息,请参见Solution User Options (.Suo) File

旁注,在您的代码示例中,main 缺少 ()

【讨论】:

  • 是的,这几乎解释了一切。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多