Re: How to create a class that casting to int explicitly only?
On Jul 30, 7:28 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On 30 Jul, 10:18, Tao Wang <Dancef...@gmail.com> wrote:
Hi,
I have a class Data as following
class Data{
...
};
I know if I want to cast it to int implicitly I should write like
following:
class Data{
...
public:
operator int() {...};
};
So, I can use the class like,
Data d(1234);
int a = d;
However, what I really want is that user of class Data have explicitly
cast it to int.
that is, user should write the code like:
int a = (int) d;
other than:
int a = d;
How can I make the cast to int explicitly only?
does this do what you want?
class Data
{
public:
explicit Data(int);
};
--
Nick Keighley
No, it is in wrong direction.
What I expected result is
Data d(1234);
int a = d; // error
int a = (int) d; // OK
Your solution is provide explicitly casting FROM int, rather than to
int.
How this be done?