未定义的对构造函数c ++的引用

问题描述 投票:-1回答:1

我已经搜索过并找到了解决这个问题的方法,但我觉得这有点奇怪。无论如何我的问题是这样的:

Personal.h

class Personal
{
  public:
   Personal();
   int money;
    ~Personal();

  }

Personal.cpp

#include "Personal.h"
Personal::Personal()
{
 money = 1800;
}

Personal::~Personal(){};

现在我想在main编译

main.cpp中

#include "Personal.h"
#include <iostream>
#include <vector>

int main()
{
 std::vector<Personal> test(100);

 }

当我写:g ++ -Wall main.cpp -o main它给了我:

undefine reference to Personal::Personal()
undefine reference to Personal::~Personal()

解决方案:

g++ -Wall Personal.cpp main.cpp -o main

为什么我也需要编译Personal.cpp?

或者另一个主要版本是包含而不是“Personal.h”,“Personal.cpp”

main.cpp中

#include "Personal.cpp"
#include <iostream>
#include <vector>

然后正常的g ++ -Wall main.cpp -o main工作

有人能帮我吗?

c++ constructor
1个回答
0
投票

为什么我也需要编译Personal.cpp?

因为您使用该文件中定义的函数。特别是,您使用函数Personal::PersonalPersonal::~Personal

有人能帮我吗?

确保所有函数(使用的函数)都是在您编译和链接在一起的源文件中的一个(或在所有文件中,如果是内联函数)中定义的。

© www.soinside.com 2019 - 2024. All rights reserved.