与C++ "was not declared in this scope"作斗争

Struggling with C++ "was not declared in this scope"

本文关键字:this scope in 斗争 declared C++ was not      更新时间:2023-10-16

有人能告诉我为什么我在运行这个时得到错误"name没有在作用域中声明"吗?

谢谢。

class lrn11_class{
    public:
        void setName(string x){
            name = x;
        }
        string getName(){
            return name;
        }
    private:
        string lrn11_name;
};
int main()
{
    lrn11_class lrn11_nameobject;
    lrn11_nameobject.setname("Zee");
    cout << lrn11_nameobject.getname() << endl;
return 0;
}

这应该有效-请参阅注释(BTW使用std::-为什么"使用命名空间std"被认为是坏做法?)

#include <iostream>
#include <string>
class lrn11_class{
    public:
        void setName(const std::string& x){  // Potentially saves copying overhead
            name = x;
        }
        std::string getName() const { // Look up const and its uses
            return name;
        }
    private:
        std::string name; // - Used: string lrn11_name; but functions use name!
};
int main()
{
    lrn11_class lrn11_nameobject;
    lrn11_nameobject.setName("Zee"); // Fixed typo
    std::cout << lrn11_nameobject.getName() << std::endl; // Ditto
    return 0;
}
  1. 您已经将lrn11_name声明为该类的可变成员。但在set和get函数中,您使用的是name
  2. 除了您需要调用您定义的函数之外。因此:lrn11_nameobject.setname("Zee");cout<lt;lrn11_nameobject.getname()<lt;endl

您必须使用以下代码:-

lrn11_nameobject.setName("Zee");
cout << lrn11_nameobject.getName() << endl;
  1. 确保

    #include <iostream>
    using namespace std;
    

应包括在内。