【发布时间】:2017-10-26 21:55:08
【问题描述】:
我正在从事一个涉及三维空间中的数学向量的项目(不要与vector 集合类型混淆)。我在Vector.cpp 中定义了一个class Vector,并在Vector.h 中声明。我的目录结构如下:
当我尝试构建项目时,我收到 LNK2019 未解决的外部符号错误。据我所知,我的所有三个文件都在构建路径上。
在Vector.cpp:
class Vector
{
private:
double xComponent;
double yComponent;
double zComponent;
public:
Vector(double x, double y, double z) : xComponent(x), yComponent(y), zComponent(z) {}
double dotProduct(const Vector& other) const
{
return xComponent * other.xComponent + yComponent * other.yComponent + zComponent * other.zComponent;
}
}
在Vector.h:
#ifndef VECTOR_H
#define VECTOR_H
class Vector
{
public:
Vector(double x, double y, double z);
double dotProduct(const Vector& other) const;
}
#endif
在Vectors.cpp:
#include "Vector.h"
#include <iostream>
using std::cout;
using std::endl;
int main()
{
Vector foo = Vector(3, 4, -7);
Vector bar = Vector(1.2, -3.6, 11);
cout << foo.dotProduct(bar) << endl;
return 0;
}
foo.dotProduct(bar) 是唯一发生链接器错误的地方(构造函数上没有发生错误)。我尝试了Vector 的其他一些非构造方法,它们也导致了链接器错误。为什么构造函数可以工作,而其他任何一个都不能工作?
这是尝试构建项目的输出:
1>------ Build started: Project: Vectors, Configuration: Debug Win32 ------
1>Vectors.obj : error LNK2019: unresolved external symbol "public: double __thiscall Vector::dotProduct(class Vector const &)const " (?dotProduct@Vector@@QBENABV1@@Z) referenced in function _main
1>C:\Users\John\Documents\Visual Studio 2017\Projects\Vectors\Debug\Vectors.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "Vectors.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
【问题讨论】:
-
向量应该在一个文件中声明,而不是两个。
-
@NeilButterworth 我不太确定我明白你的意思。我不需要在头文件中前向声明它以便可以在
Vectors.cpp中使用吗? -
nope - vector.cpp 应该只有方法体。还请包括实际的错误文本
-
没有。您已经在 .h 和 .cpp 文件中声明了它。请参考 C++ 教科书。
-
并且没有正确包含方法体 - 因此链接错误
标签: c++ visual-studio linker visual-studio-2017