我正在做一个涉及三维空间中数学向量的项目(不要与vector
集合类型混淆)。我有一个class Vector
定义Vector.cpp
,并宣布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 ==========
你定义了这个类两次。一次在标题中,一次在 .cpp 文件中。
在 .cpp 文件中只保留函数定义:
#include "Vector.h"
Vector::Vector(double x, double y, double z) : xComponent(x), yComponent(y), zComponent(z)
{
}
double Vector::dotProduct(const Vector& other) const
{
return xComponent * other.xComponent + yComponent * other.yComponent + zComponent * other.zComponent;
}
每次写入时class SomeClass {};
,您都定义了一个符号。命名空间中只能定义一个具有给定名称的符号。
请阅读有关声明和定义的更多信息。你可以从这里开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句