-
August 17th, 2011, 04:04 AM
#1
Operator Overloading
Hi there,
I'm trying to write a smart pointer class for an int variable but I've gotten a little stuck. Firstly, to declare a smart pointer to an int, I MUST use this line of code (As seen in the main method below):
smart_pointer s = new int();
To do this, I try to overload the "=" operator and set a pointer to an int (called "value" in the smart_pointer class) to the address of this new int. However, I get this error:
"conversion from ‘int*’ to non-scalar type ‘smart_pointer’ requested"
What am I doing wrong? I thought "new int()" returned a memory address which I could set the smart_pointer's int pointer to by overloading the "=" sign...
Thank you.
-------Code-------
#include<stdio.h>
#include<stdlib.h>
class smart_pointer{
private:
int *value;
public:
smart_pointer();
// Overwrite "=" operator.
smart_pointer &operator=(int *val){
value = val;
return *this;
}
~smart_pointer(){
delete value;
}
};
smart_pointer::smart_pointer(){
value = NULL;
}
int main(void){
smart_pointer s = new int();
return 0;
}
Tags for this Thread
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
|
Click Here to Expand Forum to Full Width
|