VS2010: 致命错误 LNK1120: 1 个未解析的外部问题 。使用模板

VS2010: fatal error LNK1120: 1 unresolved externals . Working with templates

提问人:Wade Guest 提问时间:4/9/2013 最后编辑:Drew DormannWade Guest 更新时间:4/9/2013 访问量:1953

问:

有一个简单的作业,包括班级和班级模板,在这里搜索过,似乎没有解决方案可以解决这个问题。当我尝试编译时,会出现这种情况:

1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup 1>c:\users\leanne\documents\visual studio 2010\Projects\PartC\Debug\PartC.exe : fatal error LNK1120: 1 unresolved externals

有一个使用空项目的控制台项目。谁能帮我找到问题? 这是我的代码:

#include <iostream>
using namespace std;
template<typename ItemType>
class Vec3
{
    ItemType x, y ,z;
public:
    Vec3<ItemType>(){x=0;y=0;z=0;}
    Vec3<ItemType>(const Vec3<ItemType>& other);
    Vec3<ItemType> operator+(Vec3<ItemType>);
    Vec3<ItemType> operator-(Vec3<ItemType>);
    bool operator==(Vec3<ItemType> other);
    Vec3<ItemType> operator=(Vec3<ItemType>);
    ~Vec3<ItemType>(){;}
};
template<typename ItemType>
Vec3<ItemType> Vec3<ItemType>::operator+(Vec3<ItemType> other)
{
    Vec3 temp;
    temp.x = x + other.x;
    temp.y = y + other.y;
    temp.z = z + other.z;
    return temp;
}
template<typename ItemType>
bool Vec3<ItemType>::operator==(Vec3<ItemType> other)
{
    if(x != other.x)
        return false;
    if(y != other.y)
        return false;
    if(z != other.z)
        return false;
    return true;
}
template<typename ItemType>
Vec3<ItemType> Vec3<ItemType>::operator-(Vec3<ItemType> other)
{
    Vec3 temp;
    temp.x = x - other.x;
    temp.y = y - other.y;
    temp.z = z - other.z;
    return temp;
}  
template<typename ItemType>
Vec3<ItemType> Vec3<ItemType>::operator=(Vec3<ItemType> other)
{
    x = other.x;
    y = other.y;
    z = other.z;
    return *this;
}
template<typename ItemType>
Vec3<ItemType>::Vec3(const Vec3<ItemType>& other)
{
    x = other.x;
    y = other.y;
    z= other.z;
}
template<typename ItemType>
int main()
{
    Vec3<int> v1;
    Vec3<int> v2(v1);
    Vec3<double> v3 = v2;
    v3 = v1+v2;
    v3 = v1-v2;
    if(v1==v2)
    {
        return 0;
    }
    return 0;
 }  
C++ 模板 unresolved-external

评论

0赞 Wade Guest 4/9/2013
我收到 LNK 1120 未解决的外部错误,因此无法编译
0赞 Drew Dormann 4/9/2013
完整的错误是什么?你遗漏了描述问题所在的部分。
0赞 Mark Ransom 4/9/2013
你能说得更具体一点吗?符号是什么?
0赞 Wade Guest 4/9/2013
尝试编译,出现这种情况: 1>MSVCRTD.lib(crtexe.obj):错误LNK2019:函数___tmainCRTStartup中引用了未解析的外部符号 1>C:\Users\Leanne\Documents\Visual Studio 2010\Projects\PartC\Debug\PartC.exe:致命错误LNK1120:1 个未解析的外部_main符号
0赞 Drew Dormann 4/9/2013
“未解析的外部符号_main”表示缺少名为的非模板化函数。main

答:

1赞 Jesse Good 4/9/2013 #1

您收到错误是因为您制作了一个模板:main

template<typename ItemType>
int main()

请删除 . 不允许成为模板。template<typename ItemType>main

删除它后,您将收到错误,因为 is a 并且无法转换为 .Vec3<double> v3 = v2;v2Vec3<int>Vec3<double>

评论

1赞 Mark Ransom 4/9/2013
令人惊讶的是,一旦所有相关信息都可用,答案就会跳出来。
0赞 Wade Guest 4/9/2013
是的,在我读到它的那一刻就打了我的头,谢谢你的回应!