2014-02-25 60 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