由于vector <string>而导致错误?

时间:2020-05-28 21:06:47

标签: c++

对不起,意大利面条式代码,我对C ++(或一般而言,没有编码)经验不足,但这是我的代码...也是第一次在堆栈溢出时发布,因此对格式不正确表示歉意。 最近4个小时,我一直在搜寻互联网。请告诉我这是一个简单的解决方法。 我尝试使用std :: vector成分。

//Program_2.h

#pragma once
#include <vector>
#include <string>
#include <iostream>


namespace sandwich
{
    class SandwichMaker
    {
    public:
        vector<string> ingredients;//<-- causing a few errors
        int s = 0;
        int Control();
        void Menu(int &s, vector<string> &vec);
        void PrintSandwich(vector<string> &vec);


    private:


    };
}

//Program_2.cpp

#include "Program_2.h"

using namespace std;
using namespace sandwich;


int SandwichMaker::Control()
{
    SandwichMaker swm;
    //vector<string> ingredients;
    swm.Menu(swm.s, swm.ingredients);


    while (swm.s > 0)
    {
        swm.Menu(swm.s, swm.ingredients);
    }

    system("PAUSE");
    return 0;
}

void SandwichMaker::Menu(int &s, vector<string>& vec)
{
    SandwichMaker swm;
    cout << "Please choose what you would like to do and type the ingredient (1 and 2 only)\n (0 quit, 1 add ingredient, 2 remove ingredient, 3 make sandwich): ";
    cin >> s;

    string tempIngredient = "";

    switch (s)
    {
    case 1://add
        //cout << "Enter the ingredient you are going to add.\n";
        cin.ignore();
        getline(cin, tempIngredient);
        vec.push_back(tempIngredient);
        cout << " Ingredient has been added\n";
        break;
    case 2://remove
        if (!vec.empty())
            vec.pop_back();
        else
            cout << " Nothing has been added yet\n";
        break;
    case 3: //make the sandwich
        swm.PrintSandwich(vec);
        break;
    default: 
        break;
    }
}

void SandwichMaker::PrintSandwich(vector<string>& vec)
{
    cout << "Your sandwich contains: ";
    for (size_t i = 0; i < vec.size(); i++)
    {
        cout << i << ", " << vec[i] << endl;
    }
}

无法发布图片soo链接? https://imgur.com/a/mK0UrEU因向量而吐出的所有错误。

1 个答案:

答案 0 :(得分:4)

您的using namespace std在包含Program_2.h之后之后,因此SandwichMaker类的定义没有using namespace std生效。

因此,您需要写std::vector,而不是vector,而不是std::string,而不是string

注意:不要尝试通过较早应用using namespace std来“解决”这一问题-这是一个糟糕的主意,而且编程效果不佳。参见:

Why is "using namespace std;" considered bad practice?

PS:

  • 您经常重复“三明治”一词:sandwich::SandwichMaker{}.PrintSandwich()-这些三明治不是太多吗?
  • 我认识一个做三明治的人,他从不印刷三明治。
  • 如果您有一个名为WhateverMaker的类-您通常根本根本不需要该类,可以选择一个不错的Whatever类,并且某些函数返回Whatever s。另请参见this