Declaring strings as std:string in C++

前端 未结 4 1635
花落未央
花落未央 2021-01-15 05:54

This is based on GCC/G++ and usually on Ubuntu.

Here\'s my sample program I\'ve done:

#include 

using namespace std;

int main()
{
          


        
4条回答
  •  失恋的感觉
    2021-01-15 06:22

    First problem:

    First of all, you are missing the #include directive. You cannot rely on other headers (such as ) to #include the header automatically. Apart from this:

    Second problem:

    Writing the string declaration as std:string also works fine. What's the difference.

    That is because you have an (evil) using directive at global namespace scope:

    using namespace std;
    

    The effect of this directive is that all names from the std namespace are imported into the global namespace. This is why the fully-qualified std::string and the unqualified string resolve to the same type.

    If you omitted that using namespace std; directive, you would get a compiler error when using the unqualified string name.

    Third problem:

    If I use this std::string within a class to declare a private variable, I get an error error: ‘std’ does not name a type. Example of this declaration:

    You are missing a colon. That should be:

    std::string
    //  ^
    

    And not

    std:string
    // ^
    

提交回复
热议问题