2017-10-26 15 views
0

저는 3 차원 공간에서 수학 벡터를 포함하는 프로젝트를 진행하고 있습니다 (vector 콜렉션 유형과 혼동해서는 안됩니다). 나는 class VectorVector.cpp에 정의하고 Vector.h로 선언했다. 다음과 같이 내 디렉토리 구조는 다음과 같습니다두 파일이 같은 디렉토리에 있어도 왜 링커 오류가 발생합니까?

Directory structure of project Vectors

내가 프로젝트를 빌드 할 때, 나는 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 " ([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

벡터는 하나의 파일로 선언해야하며 둘 다 선언해서는 안됩니다. –

+0

@NeilButterworth 나는 당신이 무슨 뜻인지 잘 모르겠다. 'Vectors.cpp'에서 사용할 수 있도록 헤더 파일에 전달 선언을 할 필요가 없습니까? – train1855

+0

nope - vector.cpp는 메서드 본문 만 있으면됩니다. 또한 실제 오류 텍스트 – pm100

답변

2

당신은 두 번 클래스를 정의했다. 머리글에 한 번, .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 {}; 쓸 때마다, 당신이 기호를 정의합니다. 이름 공간에 정의 된 주어진 이름을 가진 기호 하나만있을 수 있습니다.

선언 및 정의에 대해 자세히 읽으십시오. 당신은 start here 일 수 있습니다.

+1

감사합니다. 모든 코드가 가정 된 것으로부터 배운 C++ 책은 하나의 파일로 작성되었으므로 혼란 스럽습니다. – train1855

+0

@ train1855 환영합니다! 해피 코딩! :) – ivanmoskalev