Re: what is meant by ?
- From: "John Carson" <jcarson_n_o_sp_am_@xxxxxxxxxxxxxxx>
- Date: Thu, 14 Apr 2005 17:23:22 +1000
"IceColdFire" <IceColdFire@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:6123E31A-ED23-4EA4-A0FD-D5507A2CF429@xxxxxxxxxxxxx
Hi,
what is meant by operator int() { return i; }
in a class?
a.a.cpp
It is a cast or conversion operator. It means that you can use an object of the class in a context where you would normally use an int and the operator will substitute i for the class object, e.g.,
class Test
{
public:
Test(int i_) : i(i_)
{}
operator int() { return i; }
private:
int i;
};int main()
{
Test t(6);
// here we assign the Test object t to the int x. The conversion
// operator gets called, so we actually assign t.i to x
int x = t;return 0; }
Conversion operators can be used quite generally. A class might have more than one so that, chameleon-like, it can take on various forms as the context requires.
While sometimes convenient, conversion operators can be dangerous in that,
if you make a mistake and use a class object some place where you shouldn't, the conversion operator may allow the code to compile and thereby stop you from discovering the mistake. In other words, conversion operators compromise type safety to some extent.
-- John Carson
.
- References:
- what is meant by ?
- From: IceColdFire
- what is meant by ?
- Prev by Date: Re: what is meant by ?
- Next by Date: pointer: const to non-const assignment error
- Previous by thread: Re: what is meant by ?
- Next by thread: Smart pointer class definition missing!
- Index(es):
Relevant Pages
|