在 C++ 中,为什么可以将 int 变量声明为 class 的私有数据成员,而不是字符串变量?

In C++ why is it that int variable can be declared as private data member of a class, but not string variable?

在C++中以下头文件是合法的

#ifndef    SAMPLE_H_
#define    SAMPLE_H_

class Sample {
    private:
        int number;
};

#endif

但是下面的头文件是非法的

#ifndef
#define

class Sample {
    private:
        string name;
};

#endif

为什么会这样?

在我的例子中,我有以下头文件:

Alphabet.h

#include <string>

#ifndef         ALPHABET_H_
#define         ALPHABET_H_


class Rhyme {

private:
    string a;

public:

    Rhyme ();

};

#endif

Alphabet.cpp

#include <iostream>
#include "Alphabet.h"

using namespace std;

Rhyme::Rhyme () {

    a = "A for Apple";
}

Main.cpp

#include <iostream>
#include "Alphabet.h"

using namespace std;

int main () {

    Rhyme rhyme;
    return 0;
}

Linux终端命令:

g++ *.cpp
./a.out

在此之后我收到以下错误:

错误:

    In file included from Alphabets.cpp:2:0:
Alphabet.h:10:2: error: ‘string’ does not name a type
  string a;
  ^
Alphabets.cpp: In constructor ‘Rhyme::Rhyme()’:
Alphabets.cpp:8:2: error: ‘a’ was not declared in this scope
  a = "A for Apple";
  ^
In file included from Main.cpp:2:0:
Alphabet.h:10:2: error: ‘string’ does not name a type
  string a;

我正在尝试将 header file 中的 string member variable 声明为 private,然后使用 constructor

从另一个文件对其进行初始化

std::string 是在 header <string> 中声明的标准 user-defined class。所以你需要包括 header

#include <string>

并置于标准名称 space std 中。

所以你至少需要写

class Sample {
    private:
        std::string name;
};

在 C++ 中,int 是内置关键字,在代码中的任何位置都是有效类型。 string 是在 <string> header 中定义的 std 命名空间中的 class,只有在您首先包含 header 时才可以使用。

你不应该在 header 个文件中使用 using namespace 指令(命名空间污染),所以你需要写成 std::string.

此外,使用您的 header(例如 SAMPLE_H)的文件名来包含保护:

#ifndef SAMPLE_H
#define SAMPLE_H

#include <string>

class Sample {
    private:
        std::string name;
};

#endif