Erros C2371 and C2512!

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Please, could someone explain me why there are errors in the following code?

#include <iostream>
#include <string>
using namespace std;

class Log
{
public:
explicit Log(const string& msg) { cout << msg << endl; }
};

int main()
{
string msg = "Hello, World!";

Log(msg.c_str()); // It Works.
Log(msg); // Errors C2371 and C2512!

return 0;
}

I'm using VC++ .NET 2003.

Thanks in advance.
 
Cleber said:
Please, could someone explain me why there are errors in the following code?

#include <iostream>
#include <string>
using namespace std;

class Log
{
public:
explicit Log(const string& msg) { cout << msg << endl; }
};

int main()
{
string msg = "Hello, World!";

Log(msg.c_str()); // It Works.
Log(msg); // Errors C2371 and C2512!

return 0;
}

Log(msg); doesn't get interpreted as an call to the class constructor
(creating a temporary), but as the definition of a local variable just
as when you'd have written:

Log msg;

since you already have defined msg (as a string), you get the
redefinition error, and beacause you don't have a default constructor
defined you get the c2512.

You'll have to explictly create the temporary by using something like:

Log temp(msg);

hth
 
Thanx, Ben!

Now it's clear for me.
But, in my case, I prefer to use:

Log::Log(msg);

Thank you again!
 
Back
Top