首页 > 解决方案 > C++ 在类中使用 iostream

问题描述

我正在使用iostreammap。当我尝试设置功能时,它们会引发错误。

我的代码:

#include "string"
#include "iostream"
#include "map"

using namespace std;

class myClass {
    map<string, string> Map;
    Map["Ziv"] = "Sion";

    cout << Map["Ziv"];
};

我的错误:

error: 'Map' does not name a type
error: 'cout' does not name a type

为什么我不能使用iostreamand cout

标签: c++classdictionarycout

解决方案


为什么我不能使用 iostream 和 cout?

因为一个类不能(直接)包含表达式语句。它只能包含成员声明。

表达式语句只能在函数内。这将是正确的,例如:

class main {
    map<string, string> Map;

    void example_function() {
        Map["Ziv"] = "Sion";
        cout << Map["Ziv"];
    }
};

推荐阅读