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

回答

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

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

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

class main {
    map<string, string> Map;

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

  • @ZivSion _"I am pretty new"_ Then this should interest you: [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)

以上是C++在类中使用iostream的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>