2017-10-26 6 views
0

私は3次元空間の数学的ベクトルを含むプロジェクトに取り組んでいます(vectorコレクションタイプと混同しないでください)。私はVector.cppに定義されたclass Vectorを持っており、Vector.hと宣言しています。次のように私のディレクトリ構造は次のとおりです。両方のファイルが同じディレクトリにあるのにリンカエラーが発生するのはなぜですか?

Directory structure of project Vectors

私はプロジェクトをビルドしようとすると、私はLNK2019未解決の外部シンボルのエラーが発生します。私の知る限りでは、私の3つのファイルは全てビルドパス上にあります。

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 " ([email protected]@@[email protected]@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 ========== 
+0

ベクターは、両方ではなく1つのファイルで宣言する必要があります。 –

+0

@NeilButterworth私はあなたが何を意味しているのかよく分かりません。ヘッダーファイルに 'Vectors.cpp'で使用できるように前方宣言する必要はありませんか? – train1855

+0

nope - vector.cppにはメソッド本体が必要です。また、実際のエラーテキスト – pm100

答えて

2

あなたは二度クラスを定義しました。ヘッダーに1回、.cppファイルに1回。

.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 {};を書くたびに、あなたはシンボルを定義します。名前空間に定義された特定の名前を持つシンボルは1つだけです。

宣言と定義について詳しくお読みください。あなたはstart hereです。

+1

ありがとうございます。私がすべてのコードを仮定して学んだC++の本は、1つのファイルに書かれていたので、私の混乱です。 – train1855

+0

@ train1855ようこそ!ハッピーコーディング! :) – ivanmoskalev

関連する問題