简体   繁体   中英

error: ‘Name’ was not declared in this scope

What is the mistake in this code? I'm trying to pass a value from the constructor, but getting an error:

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

The error is:

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

For starters there is a typo. There is a missed semicolon

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

The standard class std::string is declared in the namespace std . So you have to use either the qualified name std::string in the class definition or to use the using declaration

using std::string;

before the class definition.

And remove the redundant using directive

using namespace std;

The member functions of the class could be declared and defined the following way

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

Though the constructor could be defined simpler

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM