c++ - 将由类组成的 vector 传递给函数 (C++)

标签 c++ class vector

我在这方面遇到了很多问题,主要是我传递的我的类的 Vector 不断被标记为未声明的标识符。任何解决问题的帮助或帮助我弄清楚我不明白的解释都将不胜感激。

所以这是我现在拥有的简化版本:

主要.cpp

#include "functions.h"
#include "vehicle.h"

int main()
{
   int menuSelection;

   vector<Vehicle> inventory;

   do
   {
        cout << "Please make a selection:" << endl << endl;
        cout << "1:   Display Inventory" << endl;
                     .......
        cout << "8 : Write inventory to file and exit" << endl << endl;

        if (menuSelection == 1)
        {
            if (inventory.empty())
                cout << "Database empty" << endl;
            else
                display(inventory);
                     .......
    } while (menuSelection != 8);

    return 0;
}

车辆.h

#pragma once
#include "functions.h"

class Vehicle
{
   private:
         string VIN;
         int year;
                    .......
//   public:
//        string getVIN();
                    .......
}

函数.h

#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void display(vector<Vehicle>);
                    .......

void display(vector<Vehicle>& in)
{
        Vehicle v;
        cout << "VIN: " << v.getVIN(in)
}
                    .......

我已经尝试了很多不同的方法来让它工作,所以这就是为什么很多东西看起来像是奇怪的语法(我也不是很好)。我的任务是在 main.cpp 中有一个菜单,它将从存储在 vehicle.h 中的类中创建一个 vector ,然后该菜单应该调用位于 functions.h 中的函数,这些函数将通过 vehicle.h 与第四个不包括 vehicle.cpp 来处理类中的信息。

最佳答案

functions.h , void display(vector<Vehicle>);不编译因为 Vehicle此时未声明。

另外,在 functions.h , void display(vector<Vehicle>& in)是与先前原型(prototype)不同的重载(& 有所不同),可能不是您想要的。然后你在 functions.h 中放置一个函数体-- 这不应该在那里。

您需要组织代码以便 Vehicle类定义出现,然后是functions.h包括那个。


所以 vehicle.h应该看起来像:

#pragma once
#include <string>
// do NOT include functions.h

class Vehicle
{
  // ...
};

然后 functions.h应该看起来像:

#pragma once
#include "vehicle.h"
// do NOT do "using namespace std;" in a header and don't include any unnecessary headers

void display(vector<Vehicle> &in);

然后 functions.cpp应该#include "functions.h"并包含 display 的函数体.

关于c++ - 将由类组成的 vector 传递给函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33797223/

相关文章:

c++ - 在 C++ 中鸭子打字(通过其非类型模板参数的值专门化模板函数)

c++ - 使用 std::variant 的递归 typedef 定义

C++调用时指定函数的非模板版本

c++ - 如何添加和读取两种类型变量的 vector 元素

c++ - 模板类自动类型转换的运算符重载

c++ - 如何生成和使用带有 new 的 c++11 std::array 以使用堆而不是堆栈?

c++ - 不同的 rand() 序列在表达式中产生相同的结果

c# - 正确的单例类实现

c++ - 是什么让这段代码变得糟糕

ruby - 包含一个模块来定义动态类方法