Let me show you this simple example to illustrate what conversion functions are:
class MyString
{
public:
MyString(const char * ch = "") : _value(ch) {}
virtual ~MyString();
operator const char * () { return _value; }
private:
const char * _value;
};
Here, the operator function is a conversion function that allows the
MyString class to be cast as a const char *, as shown below:
#include <iostream>
#include <string>
#include "MyString.h"
int main ()
{
MyString ms("Hello World!");
std::cout << "MyString ms is " << ms << std::endl; //!==> USE CASE 1
ms = "hehehe";
std::cout << "MyString ms is " << ms << std::endl;
if (ms == "hehehe") //!==> USE CASE 2
std::cout << "ms matches const char * !!!" << std::endl;
else
std::cout << "nope." << std::endl;
std::string str = "hehehe";
if (str == static_cast<const char *>(ms)) //!==> USE CASE 3
std::cout << "ms matches std::string !!!" << std::endl;
else
std::cout << "nope." << std::endl;
return 0;
}
The output is as follows:
MyString ms is Hello World!
MyString ms is hehehe
ms matches const char * !!!
ms matches std::string !!!
As we can see, the conversion function allowed
MyString to be treated as const char *. In use case 1, the streaming operator converts ms. In use case 2, we have the equality operator calling the conversion. In use case 3, however, std::string's equality operator does not call the conversion function. Hence, we need to cast it explicitly. Without the conversion function in MyString, the three use cases would have generated compilation errors.That's all for now. Ta-ta!
-- Allister (http://cxxpython.blogspot.com)

No comments:
Post a Comment