View Single Post
Old Apr 30th, 2008, 5:59 AM   #1
JD-Salinger
Unknown
 
JD-Salinger's Avatar
 
Join Date: Apr 2008
Location: unknown
Posts: 87
Rep Power: 1 JD-Salinger is on a distinguished road
copy constructors explanation and o.overloading

I just need some little explanation about this snippet, i did some little experiment in the class "value" and when i compiled the source file, error pops out, even though in my own logic, there is nothing wrong with it, i came with this book and im trying to learn copy constructors and operator overloading and i did some experimenting on the code:

This is the original code:
c++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. using namespace std;
  5.  
  6. class Value
  7. {
  8. public:
  9. Value()
  10. {
  11. cout<<" Default constructor\n";
  12. _numString=new char[1];
  13. _numString[0]= '\0';
  14. }
  15.  
  16. Value(int i)
  17. {
  18. cout<< "Construction/conversion from int "<<i<<endl;
  19.  
  20. stringstream buffer;
  21. buffer<< i <<ends; //terminate sring
  22. Init(buffer.str().c_str());
  23. Display();
  24. }
  25.  
  26. Value(Value const& v)
  27. {
  28. cout<< " Copy constructor("
  29. << v._numString<< ")\n";
  30. Init(v._numString);
  31. Display();
  32. }
  33.  
  34. Value& operator= (Value const& v)
  35. {
  36. cout<<"operator=("
  37. <<v._numString
  38. <<")\n";
  39.  
  40. if(_numString != v._numString)
  41. {
  42. cout<<"not equal"<<endl;
  43. delete _numString;
  44. Init(v._numString);
  45. }
  46. Display();
  47. return *this;
  48. }
  49.  
  50. friend Value operator+ (Value const& v1,Value const& v2)
  51. {
  52. cout<<" operator+ ("<<v1._numString<< ", "
  53. <<v2._numString <<")\n";
  54.  
  55. stringstream buffer;
  56. buffer<<v1._numString<< " + "<<v2._numString<<ends;
  57. Value result;
  58. result.Init(buffer.str().c_str());
  59. cout<<" Returning by value\n";
  60. return result;
  61. }
  62.  
  63. private:
  64.  
  65. void Init(char const* buf)
  66. {
  67. int len=strlen(buf);
  68. _numString=new char[len + 1];
  69. strcpy(_numString,buf);
  70. }
  71.  
  72. void Display()
  73. {
  74. cout<< "\t" <<_numString<<endl;
  75. }
  76.  
  77. char* _numString;
  78. };

now what I did is that on line 50 i replaced it to
inline Value operator+ (Value const& v1,Value const& v2)
then the error is "must take zero to one argument"

and i also replaced line 50 to
Value& operator+ (Value const& v1,Value const& v2)
and still same error....

im wondering what's the explanation behind this, i just copied line 34... Thanks
__________________
-------------------------------------------------------------------------
I thought what I'd Do was, I'd pretend to be one of those deaf mutes
------------------------------------------------------------------------
JD-Salinger is offline   Reply With Quote