2

每次我编译 function.cpp 文件时都会收到一个错误,说 stock 和 newStock 没有在这个范围内声明。我正在尝试在向量中使用结构。谢谢您的帮助。

这是 main.cpp 文件

#include <fstream>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <sstream>
#include <vector>
using namespace std;

struct Stocks
{
    int one;
    int two;
    int three;
};

vector<Stocks> portfolio;

#include "testProject2.h"

int main()
{
buyStock(portfolio);

} 

这是头文件。

#include <iostream>

void buyStock(vector<Stocks>& Portfolios);

这是function.cpp文件

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

void buyStock(vector<Stocks>& Portfolios)
{
Stocks newStock;
newStock{1,2,3};
Portfolios.push_back(newStock);
}
4

2 回答 2

3

您的 function.cpp 文件无法知道 Stocks 结构是什么。在头文件中定义:

struct Stocks {
   int one;
   int two;
   int three;
};

并从 main.cpp 中删除它的定义。

同样在你的头文件中,你需要

#include <vector>

并将向量参数称为std::vector<Stocks> &Portfolios(优于using namespace std;

您的初始化语法newstock{1,2,3}看起来也不正确。

于 2018-04-28T03:54:33.407 回答
2

vector在未定义的情况下在头文件中使用。

尝试将头文件更改为:

#include <vector>
#include <Stocks.h> // name of .h file where Stocks is defined

void buyStock(std::vector<Stocks>& Portfolios);

// OR

using namespace std::vector;
void buyStock(vector<Stocks>& Portfolios);
于 2018-04-28T03:50:18.213 回答