Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring strings as std:string in C++

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

Here's my sample program I've done:

#include <iostream>

using namespace std;

int main()
{
    std::string c = "Test";
    cout << c;
    return 0;
}

The above code works fine.

But I have two issues that I don't quite get...

  1. Writing the string declaration as std:string (with one :) also works fine. What's the difference?

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

class KType
{
private:
    std:string N;
};

Can someone please explain these issues? Many thanks!

like image 474
itsols Avatar asked May 30 '26 05:05

itsols


1 Answers

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

The difference would be slight clearer if you formatted it differently:

std:
    string c = "Test";

You're declaring a label called std, and using the name string which has been dumped into the global namespace by using namespace std;. Writing it correctly as std::string, you're using the name string from the std namespace.

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.

That's because you can't put a label in a class definition, only in a code block. You'll have to write it correctly as std::string there. (If the class is defined in a header, then using namespace std is an even worse idea than in a source file, so I urge you not to do that.)

Also, if you're using std::string, then you should #include <string>. It looks like your code works by accident due to <iostream> pulling in more definitions than it need to, but you can't portably rely on that.

like image 67
Mike Seymour Avatar answered Jun 01 '26 18:06

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!