What is the meaning of 'class & address operator' in the factor?

Asked 2 years ago, Updated 2 years ago, 23 views

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;
}

c++

2022-09-22 20:39

1 Answers

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.


2022-09-22 20:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.