简体   繁体   中英

confused in copy constructor and objects in C++

I saw the others question on Stack Overflow but they only answered a part of it.
suppose we have a class-

class student
{
public:    
    string name;    
    student(string a)
    {
        name = a;
        cout << "parmeteised const." << endl;
    }

    student(student &a)
    {
        name = a.name;
        cout << "Copy const." << endl;
    }
};

int main()
{
    student a("Vyom");
    student c(a);
    if (a == c)
    {
        cout << "same";
    }
    return 0;
}

This does not compile and gives an error-

no operator "==" matches these operands -- operand types are: student == student

Now I know that this is wrong and I would have to overload the operator to do so.

My Doubts:

  1. We have argument &a in the copy constructor but we input only a while making an object c .
  2. If point 1 is true and valid then it probably means a stands for the memory location of the object.
  3. if point 2 is true and valid then why can't I compare memory locations of a and c
    (I know memory locations will be in hexadecimal but there must be a way to convert them into int and then compare).
    I am beginner, please help me clarify my doubts.
  1. We have argument &a in the copy constructor but we input only a while making an object c.

In the function student(student &a) variable 'a' is reference on a student. It is not a pointer ( student* a ).

You will have to implement the comparison operator == if you want to compare two student objects: operator_comparison

You have to overload (implement) == operator for the class. Below is a sample == operator implementation for your class -

bool operator==(const student& a) const {
    if (a.name == this->name) return true;
    
    return false;
  }

Now your code should look like below -

#include <iostream>
using namespace std;
class student
{
public:    
   string name;    
   student(string a)
   {
    name = a;
    cout << "parmeteised const." << endl;
}

student(student &a)
{
    name = a.name;
    cout << "Copy const." << endl;
}

bool operator==(const student& a) const {
    if (a.name == this->name) return true;
    
    return false;
  }
};

int main()
{
   student a("Vyom");
   student c(a);
   if (a == c)
   {
       cout << "same";
   }
   return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM