Skip to content

Instantly share code, notes, and snippets.

@behitek
Last active November 7, 2016 13:17
Show Gist options
  • Save behitek/268a35c46b697ed99dbb408564b627b8 to your computer and use it in GitHub Desktop.
Save behitek/268a35c46b697ed99dbb408564b627b8 to your computer and use it in GitHub Desktop.
Overload operator = in C++
// http://stackoverflow.com/questions/3933637/why-cannot-a-non-member-function-be-used-for-overloading-the-assignment-operator
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
class complex{
protected:
int a,b,i;
float *v;
public:
complex(){
a=b=i=0;
}
void add(){
cout<<"Nhap phan thuc a : ";cin>>a;
cout<<"Nhap phan ao b : ";cin>>b;
}
void display(){
if(b>0){
cout<<a<<" + "<<b<<"i";
}else{
cout<<b<<"i"<<" + "<<a;
}
}
friend complex operator +(complex aa,complex bb);
friend complex operator -(complex aaa,complex bb);
complex operator =(complex t);
};
complex operator +(complex aa,complex bb){
complex c;
c.a=aa.a+bb.a;
c.b=aa.b+bb.b;
return c;
}
complex operator -(complex aaa,complex bbb){
complex cc;
cc.a=aaa.a-bbb.a;
cc.b=aaa.b-bbb.b;
return cc;
}
complex complex::operator =(complex v){
a=v.a;
b=v.b;
return (*this);
}
int main(){
complex b;
b.add();
complex a=b;
a.display();
/* complex b[2];
for(int i=0;i<2;i++){
b[i].add();
}
complex tong;
for(int i=0;i<2;i++){
tong=tong+b[i];
}
tong.display();
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment