使用std:string名称的类中的字符串

Strings in classes using std:string name

本文关键字:字符串 std string 使用      更新时间:2023-10-16

我遇到了一个错误,告诉我字符串不是类型。我查了一下这里,发现std::string name;在头文件中,但是当我编译程序时,它告诉我name没有在作用域中声明。

这是我的代码头:

#ifndef INMATE_H
#define INMATE_H
#include <iostream>
#include <string>
class Inmate
{
public:
    Inmate();
    int getID();
    std::string getName();
    //int getHeightFt();
    //int getHeightInch();
    void setID(int x);
    //void setName():
    //void setHeightFt();
    //void setHeightInch();
private:
    int idNumber;
    std::string name;
    //int heightFt;
    //int heightInch;
};
#endif // INMATE_H

这是我的CPP文件代码

#include "Inmate.h"
#include <iostream>
#include <string>
using namespace std;
Inmate::Inmate()
{
    cout << "What is the inmates name"<<endl;
    cin >> name;
}
void Inmate :: setID(int x){
    idNumber = x;
}
int Inmate :: getID(){
    return idNumber;
}
string getName(){
    return name;
}

您在getName()方法上忘记了Inmate前缀。

string Inmate::getName(){
    return name;
}

如果没有前缀,则函数getName存在于全局作用域中,而name在全局作用域中解析,而不是在类作用域中解析。由于全局作用域中没有name变量,编译器会报告一个错误。