2014-02-25 65 views
-1

所以我有一個類y被使用的類x,它也將被其他類使用。錯誤未定義的引用.. C++?

.H類X

#pragma once 
#include <string> 
#ifndef X_H 
#define X_H 
class x 
{ 
public: 
    x(); 
    const std::string & getName() const; 
    int getQuantity(); 

private: 
    std::string name; 
    int quantity; 
}; 
#endif 

的.cpp對於x

#include <string> 
#include "x.h" 
using namespace std; 



x::x() 
: name(),quantity(0) 
{ 
} 
const string & x::getName() const 
{ 
return name; 
} 
const string & x::getQuantity() const 
{ 
return quantity; 
} 

這是類.Hÿ

#pragma once 
#include <string> 
#include <array> 
#include "x.h" 

class y 
{ 
public: 
    static const size_t number = 20; 

    y(); 
    float getTotal(); 

private: 
    std::array<X*, number> arrayList; 
}; 

並且這對於類在.cpp Ÿ

#include "y.h" 
#include "x.h" 
#include <array> 
#include <string> 
#include <iostream> 

using namespace std; 

y::y() 
: arrayList() 
{ 
} 

float y::getTotal() 
{ 
    float total=0.0; 
    for(int i=0; i< number; i++) 
    { 
     if(arrayList[i] != nullptr) 
     { 
      total += arrayList[i]->getQuantity(); 
     } 
    } 
} 

方法在y類使用指針方法Y的數組,我想使用數組成員使用從類X的一些方法,但我得到一個錯誤說:

undefined reference to `x::x(...) 

我認爲它有與預處理器或標題有關。

+0

缺少類「X」整個實現其定義(x.cpp)? – loentar

+0

對不起,我只是沒有粘貼。我現在將 – user3348712

回答

0

這意味着,你忘了定義默認構造函數X :: X()或一些其他的構造函數的參數(這是什麼X :: X(...)是什麼意思?)類X的你只宣稱它在類定義。 或者另一個原因是具有構造函數定義的模塊未包含在項目構建中。

+0

我有一個x.cpp定義構造函數及其所有方法。關於y.cpp中使用的所有x方法,我得到同樣的錯誤。 – user3348712

+0

@ user3348712這表示目標文件未包含在構建中。 –

0

在課堂x已顯式聲明的默認構造函數X(),但你有沒有定義它。如果您想使用默認的構造函數,刪除其定義或x::x():name(std::string()),quantity(0){}

+0

對不起,我沒有粘貼x.cpp,但現在我已經。 – user3348712