Start New Discussion within our Software Development Community

What is the difference between these two and why does one compile fine compared to the other :S

//MyFile.h
#include<iostream>
using namespace std;

inline std::ostream& operator << (std::ostream& Str, const RGB &Rgb)
{
    Str<<"R: "<<(int)Rgb.R<<"  G: "<<(int)Rgb.G<<"  B: "<<(int)Rgb.B;
    return Str;
}


//Main.cpp

#include <iostream>
#include "MyFile.h"

using namespace std;

int main()
{
   cout<<Rgb(16777215);      //Results in an error!
}

The above gives an error but the below thing does not:

//Main.cpp

#include <iostream>

using namespace std;

inline std::ostream& operator << (std::ostream& Str, const RGB &Rgb)
{
    Str<<"R: "<<(int)Rgb.R<<"  G: "<<(int)Rgb.G<<"  B: "<<(int)Rgb.B;
    return Str;
}

int main()
{
   cout<<Rgb(16777215);      //Results are printed correctly.
}

Neither of the code snippets you posted compile. This is your second example with a couple changes so that I could make it compile, but it also has a problem.

The operator << has two parameters, but main() is passing only one parameter. Fix that and both examples will compile.

#include <iostream>

using namespace std;
struct RGB
{
    int R, G, B;
};

inline std::ostream& operator << (std::ostream& Str, const RGB &Rgb)
{
    Str<<"R: "<<(int)Rgb.R<<"  G: "<<(int)Rgb.G<<"  B: "<<(int)Rgb.B;
    return Str;
}

int main()
{
    RGB Rgb;
   cout<<Rgb(16777215);      
Comments
Thank you
This question has already been answered. Start a new discussion instead.