Why am I getting string does not name a type Error?

前端 未结 5 1865
Happy的楠姐
Happy的楠姐 2020-11-29 19:02

game.cpp

#include 
#include 
#include 
#include \"game.h\"
#include \"         


        
相关标签:
5条回答
  • 2020-11-29 19:22

    Just use the std:: qualifier in front of string in your header files.

    In fact, you should use it for istream and ostream also - and then you will need #include <iostream> at the top of your header file to make it more self contained.

    0 讨论(0)
  • 2020-11-29 19:22

    Try a using namespace std; at the top of game.h or use the fully-qualified std::string instead of string.

    The namespace in game.cpp is after the header is included.

    0 讨论(0)
  • 2020-11-29 19:26

    You can overcome this error in two simple ways

    First way

    using namespace std;
    include <string>
    // then you can use string class the normal way
    

    Second way

    // after including the class string in your cpp file as follows
    include <string>
    /*Now when you are using a string class you have to put **std::** before you write 
    string as follows*/
    std::string name; // a string declaration
    
    0 讨论(0)
  • 2020-11-29 19:34

    Your using declaration is in game.cpp, not game.h where you actually declare string variables. You intended to put using namespace std; into the header, above the lines that use string, which would let those lines find the string type defined in the std namespace.

    As others have pointed out, this is not good practice in headers -- everyone who includes that header will also involuntarily hit the using line and import std into their namespace; the right solution is to change those lines to use std::string instead

    0 讨论(0)
  • 2020-11-29 19:36

    string does not name a type. The class in the string header is called std::string.

    Please do not put using namespace std in a header file, it pollutes the global namespace for all users of that header. See also "Why is 'using namespace std;' considered a bad practice in C++?"

    Your class should look like this:

    #include <string>
    
    class Game
    {
        private:
            std::string white;
            std::string black;
            std::string title;
        public:
            Game(std::istream&, std::ostream&);
            void display(colour, short);
    };
    
    0 讨论(0)
提交回复
热议问题