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:
&a
in the copy constructor but we input only a
while making an object c
.a
stands for the memory location of the object.a
and c
- 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.