-
operator overloading and built-in types
i apologize if this is a beat to death question, but i can't find a clear
answer anywhere.
suppose i've defined a class called altInt, and i've overloaded the assignment
operator.
// this i know how to do
altInt b(5), b2(50); // constructor initializes to 5 and 50
int i = 10;
b2 = b;
b2 = i;
// but is there a way to do this?
i = b2;
-
Re: operator overloading and built-in types
You could overload the cast operator but this must be used with caution as
it can lead to unneeded side effects (think carefully and you'll work out
what they are...)
class altInt
{
int memberint;
public:
operator int(void)
{
return memberint;
}
};
This will make all instances of 'altInt' appear to be 'int' where necessary.
"michelle" <michelle.donalies@hamptonu.edu> wrote in message
news:3a6dfa29$1@news.devx.com...
>
> i apologize if this is a beat to death question, but i can't find a clear
> answer anywhere.
>
> suppose i've defined a class called altInt, and i've overloaded the
assignment
> operator.
>
> // this i know how to do
> altInt b(5), b2(50); // constructor initializes to 5 and 50
> int i = 10;
> b2 = b;
> b2 = i;
>
> // but is there a way to do this?
> i = b2;
-
Re: operator overloading and built-in types
"michelle" <michelle.donalies@hamptonu.edu> wrote:
>
>i apologize if this is a beat to death question, but i can't find a clear
>answer anywhere.
actually, this is an interesting one.
>
>suppose i've defined a class called altInt, and i've overloaded the assignment
>operator.
>
>// this i know how to do
>altInt b(5), b2(50); // constructor initializes to 5 and 50
>int i = 10;
>b2 = b;
>b2 = i;
>
>// but is there a way to do this?
>i = b2;
yes. but look at what the function actually is. i.operator=(b2);
i has no overloaded assignment operator. so what you need to do is somehow
promote i to be an altint instead of an int. to do this, you need to implement
a global function. since there is no int::operator=(altint) function, the
compiler will then look for a matching prototype in the global namespace.
the following would do the trick... ::operator=(altint, altint)....this,
you can provide... it would like somewhat like:
class alt_int
{
public:
alt_int(int i) : m_i(i) { }
int get() const { return m_i; }
private:
int m_i;
};
int operator+(const alt_int& ai1, const alt_int& ai2)
{
return ai1.get() + ai2.get();
}
int main()
{
int i(5);
alt_int ai(4);
int test1(i + ai);
int test2(ai + i);
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks