The code below is a code that performs a substitution calculation with deep radiation. If you look at the annotated line, it says Student&operator= (Student&ref Can you make a constructor like that? What does that mean? When I studied pointers, I learned that this address value is to return and refer to... I don't know what it means to write '&variable name(?)' and assignments '=' and 'class name&variable name' right next to the constructor. ㅠ<
#include <iostream>
using namespace std;
class Student
{
private:
char * name;
int age;
public:
Student(char * name, age) : age(age) // The form of the constructor that I have often seen. (+member initializer)
{
this->name = new char[10];
strcpy(this->name, name);
}
void ShowInfo() {
cout << "Name: " << name << endl;
cout << "Age:" <<age << endl;
}
Student&operator= (Student&ref) // But I'm not sure about this constructor.
{
delete []name;
name = new char[10];
strcpy(name, ref.name);
age = ref.age;
return *this;
}
~Student()
{
delete []name;
cout <<"~Student extinction call!" <<endl;
}
};
int main()
{
Student st1 ("Kim Chul-soo", 14);
Student st2 ("Hong Gil-dong", 15);
st2 = st1;
st1.ShowInfo();
st2.ShowInfo();
return 0;
}
The constructor is not a constructor because it must not have a function name.
You'll understand if you study operator overloading.
Student& operator=(Student& ref)
(Return) (Function name) (Factor)
If you look at it, there's a function called operator=, right? Common function.
It's a function called operator=, and the factor is Strudent's reference type, and it's returned by Student's reference. At the end, return *this; returns the pointer, right? So there's a reference type as a return.
operator This type of function is used to overload the operator.
Use to override operators such as +, -, =, <<, etc. by covering them.
In the main function,
st2 = st1;
There's a code, and if you just do it, the variables in st1 will normally be substituted in st2.
If a member variable has a pointer format, it would be the same, but since the pointer's substitution is a simple reference, the two pointers point to the same value. Later, when the destructor is called, the same reference value is lost, and there is a memory leak problem due to the deletion of the deleted value and the failure to delete other values.
Seeing this as a problem caused by shallow copying, what we do is use deep copying.
Use operator overloading, which overwrites the "=" operation given here to be a shallow copy and redefines it to be a deep copy.
529 Uncaught (inpromise) Error on Electron: An object could not be cloned
547 Who developed the "avformat-59.dll" that comes with FFmpeg?
546 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
695 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.