yungman
- 5,741
- 294
I have been working on making a deep copy of sum in operator+() by putting sum outside of the function so it doesn't not get destroyed when exit the function. I still run into problems I tested using strncpy_s for object First, Second works and display accordingly. but the problem is with operator+(). I don't know any better how to fix it. Please give me some guidance. This is really beyond my knowledge, it's hard to take a hint at this point.
Here is my work, I made it as short as possible for easy reading.
This is main:
Here is the header file:
This is the error list:
Please advice whether this is the right way to have deep copy.
Thanks
Here is my work, I made it as short as possible for easy reading.
This is main:
C++:
#include <iostream>
#include "OverLoad.h"
#include <cstring>
using namespace std;
int main()
{ const int size = 25; char Ara[size] = "First", Arb[size] = "Second", Arc[size] = "Result";
Vec First(Ara, 1, 2);
cout << " In main, " << First.name << "(" << First.x << "," << First.y << ")\n\n";
Vec Second(Arb, 3, 4);
cout << " In main, " << Second.name << "(" << Second.x << "," << Second.y << ")\n\n";
Vec Result(Arc);
cout << " In main, " << Result.name << "(" << Result.x << "," << Result.y << ")\n\n";
// Cannot use overload =
Result = First + Second;
//Cannot read Result.x, Result.y
cout << " (" Result.x << "," << Result.y << ") = (" << First.x << "," << First.y <<
") = (" << Second.x << "," << Second.y << ") \n\n";
return 0;
}
Here is the header file:
C++:
#ifndef OverLoad_H
#define OverLoad_H
#include <iostream>
#include <cstring>
using namespace std;
class Vec
{
public:
double x, y;
char sumName[25] = "sum"; char name[25];
Vec sum() { x = 0; y = 0; strncpy_s(name, 25, sumName, 25); }//OK, declaring Vec sum.
Vec(char* desc)//work
{ x = 0; y = 0;
strncpy_s(name, 25, desc, 25);
}
Vec(char* desc, double x0, double y0)//work
{ x = x0; y = y0;
strncpy_s(name, 25, desc, 25);//Copy First or Second into name.
}
void operator+ (const Vec& rhs) const//sum is public, no need to return
{ sum.x = x + rhs.x; sum.y = y + rhs.y;} //Problem using sum
Vec &operator=(Vec &right)
{x = right.x; y = right.y; return *this;}
};
#endif
This is the error list:
Please advice whether this is the right way to have deep copy.
Thanks