[Assorted-commits] SF.net SVN: assorted: [672] sandbox/trunk/src/cc/conversions.cc
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-04-21 19:52:36
|
Revision: 672 http://assorted.svn.sourceforge.net/assorted/?rev=672&view=rev Author: yangzhang Date: 2008-04-21 12:52:35 -0700 (Mon, 21 Apr 2008) Log Message: ----------- conversions demo Modified Paths: -------------- sandbox/trunk/src/cc/conversions.cc Modified: sandbox/trunk/src/cc/conversions.cc =================================================================== --- sandbox/trunk/src/cc/conversions.cc 2008-04-21 19:52:14 UTC (rev 671) +++ sandbox/trunk/src/cc/conversions.cc 2008-04-21 19:52:35 UTC (rev 672) @@ -1,15 +1,38 @@ +// Demo of conversions. + #include <iostream> +#include <string> using namespace std; +void f(const string& str) { + cout << "f(const string& str = " << str.c_str() << ")" << endl; +} + +void f(bool b) { + cout << "f(bool b = " << b << ")" << endl; +} + int main() { - // This doesn't compile. + // This lexical conversion doesn't compile. // int i("321"); // This doesn't work as expected; always outputs 1. bool b("false"); cout << b << endl; + + // What happens is that C++ can't find an exact match for a "const char*" parameter. It looks at all the available constructors, and looks at which ones are possible. There are two: + // + // 1. bool via a pointer -> bool conversion + // 2. std::string via the std::string(const char*) constructor + // + // 1. is a "standard conversion sequence" + // 2. is a "user-defined conversion sequence," since it is a function. + // + // C++ decides the "best" function to call by ranking all the possible calls. Standard conversions rank better than user-defined conversions, so #1 is called. + f(string("hello")); + f("hello"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |