C++ 错误:未定义对..的引用。。c++;?
所以我有一个类x,它被类y使用,它也将被其他类使用 .h代表x类C++ 错误:未定义对..的引用。。c++;?,c++,arrays,pointers,header,C++,Arrays,Pointers,Header,所以我有一个类x,它被类y使用,它也将被其他类使用 .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
#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
我认为这与预处理器或标头有关。这意味着您忘记了定义默认构造函数X::X()或具有类X的参数(X::X(…)是什么意思?)的其他构造函数。您只在类定义中声明了它。
或者另一个原因是具有构造函数定义的模块未包含在项目构建中。在类
x
中,您已明确声明默认构造函数x(),但尚未定义它。如果要使用默认构造函数,请删除其定义或使用x::x():name(std::string())、quantity(0){}
定义构造函数及其所有方法的x.cpp。关于y.cpp中使用的所有x方法,我收到了相同的错误。@user3348712这意味着对象文件未包含在生成中。缺少类“x”(x.cpp)的整个实现?抱歉,我没有粘贴它。很抱歉,我以前没有粘贴x.cpp,但现在已经粘贴了。
#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;
}
#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;
};
#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();
}
}
}
undefined reference to `x::x(...)