Ryan
Ryan

Reputation: 3215

What is the difference between these two headers?

I have these two header files and one produces an error if I don't put std:: in front of all string declarations and the other doesn't. I was just wondering what the difference between the two was.

The following will produce an error if the std:: is not in front of the string declarations:

#include <string>
#include <vector>

#pragma once

#ifndef DATABASE_H
#define DATABASE_H

struct Item
{
    public:
        std::string object;

        int numOfColors;
        std::string colors;

        int sizeSmall;
        int sizeLarge;
};

class database
{
private:
    void fillDatabase(std::vector<Item>);
public:
    void getDatabase(std::vector<Item>);
};

#endif

The following code will not produce an error:

#include <string>

#pragma once

#ifndef GUISTRUCT_H
#define GUISTRUCT_H

struct guiValues
{
    public:
        string shape;
        string color;
        int width;
        double squareProbability;
        double rectangleProbability;
        double circleProbability;

        string firstMostLikelyObject;
        double FMLOprobability;
        string secondMostLikelyObject;
        double SMLOprobability;
        string thirdMostLikelyObject;
        double TMLOprobability;

};

#endif

Upvotes: 1

Views: 138

Answers (2)

Alok Save
Alok Save

Reputation: 206526

string is declared in the namespace std. So one needs to use the namespace std to make use of string. it can be done in two ways:

By explicitly mentioning which type(string in this case) you want to include from the std namespace as in case 1, std::string colors
OR
By enabling the entire std namespace, using namespace std; which imports all types from the namespace in your global namespace.(Please note that Doing this in headers is not recommended)

In the second case seems you have included the entire std namespace before the particular include and hence it is not giving an error even without exlpicit mention of std::String

Upvotes: 2

c-smile
c-smile

Reputation: 27460

The second file is included after some other that defines

using namespace std;

Upvotes: 8

Related Questions