【问题标题】:Catching the name from a function从函数中获取名称
【发布时间】:2021-04-11 16:01:19
【问题描述】:

在尝试将值传递给构造函数时,我不断收到关于构造函数无法接受该值的错误,这是因为主类吗? :

#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();

【问题讨论】:

  • 我得到的错误比这多得多,这里有很多错别字和使用前声明错误:godbolt.org/z/8znqec
  • 由于多种原因,此代码无法编译。 Class 而不是class,类定义后没有;using namespace std 语句前没有string,等等
  • 请检查您是否复制粘贴您正在编译的实际代码
  • 当你有很多很多错误时,修复第一个错误并重新编译。如果您在这里需要帮助,您需要给我们一个具体的错误来处理 - 这有点太笼统了。
  • 如果这是 Visual Studio,我建议您查看“输出”选项卡中的错误消息,而不是错误列表,原因有两个。 1. 输出选项卡中的错误总是按正确的顺序排列, 2. 输出选项卡中的错误消息通常采用更详细的格式,这有时会有所帮助。 #1 很重要,因为很多时候一个错误可能会导致多个问题。

标签: c++ string class declaration name-lookup


【解决方案1】:

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

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 ){
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多