错误:“名称”未在此范围内声明

问题描述

这段代码有什么错误?我正在尝试从构造函数传递一个值,但出现错误:

#include <iostream>
#include <string>
using std::cout;
using std::endl;

Class GettingVal{
    public:
        GettingVal(string z){
            setName(z);
        }
        void setName(string x){
            name = x;
        }
        string getName(){
            return name;
        }
    private:
        string name;
}  
using namespace std;
int main()
{
  GettingVal Name("Hiiiiiii");
  std::cout << Name.getName();
}

错误是:

error: ‘Name’ was not declared in this scope
   std::cout << Name.getName();

解决方法

对于初学者来说,有一个错字。漏了一个分号

Class GettingVal{
   //...
};
^^^

标准类 std::string 在命名空间 std 中声明。 因此,您必须在类定义中使用限定名称 std::string 或使用 using 声明

using std::string;

在类定义之前。

并删除多余的 using 指令

using namespace std;

类的成员函数可以通过以下方式声明和定义

    GettingVal( const std::string &z){
        setName(z);
    }
    void setName( const std::string &x){
        name = x;
    }
    const std::string & getName() const {
        return name;
    }

虽然构造函数可以定义得更简单

    GettingVal( const std::string &z) : name( z ){
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...