Lecture 04
C++ Primer
CSE225: Data Structures and Algorithms
A Complex Number Example
class Complex
{ Complex Complex::Add(Complex c)
public: {
Complex(); Complex t;
Complex(double, double); [Link] = Real + [Link];
Complex Add(Complex); [Link] = Imaginary + [Link];
void Print(); return t;
private: }
double Real, Imaginary; void Complex::Print()
}; {
cout << Real << endl;
Complex::Complex() cout << Imaginary << endl;
{ }
Real = 0;
Imaginary = 0;
} int main(void)
{
Complex::Complex(double r, double i) Complex A(1,1), B(2,3);
{ Complex C;
Real = r; C = [Link](B);
Imaginary = i; [Link]();
} return 0;
}
Friend Function
The function has access to the private members in the
class declaration
The function is not in the scope of the class
Friend Function
class Complex
{
public:
Complex();
Complex(double, double);
void Print();
friend Complex AddComplex(Complex, Complex);
private:
double Real, Imaginary;
};
Complex::Complex()
{
Real = 0;
Imaginary = 0;
}
Complex::Complex(double r, double i)
{
Real = r;
Imaginary = i;
}
Friend Function
void Complex::Print()
{
cout << Real << endl;
cout << Imaginary << endl;
}
Complex AddComplex(Complex a, Complex b)
{
Complex t;
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
return t;
}
int main(void)
{
Complex A(1,1), B(2,3);
Complex C;
C = AddComplex(A, B);
[Link]();
return 0;
}
Operator Overloading
We can use some operator symbols to define special member
functions of a class
Provides convenient notations for object behaviors
Operator Overloading
class Complex
{
public:
Complex();
Complex(double, double);
Complex operator+(Complex);
void Print();
private:
double Real, Imaginary;
};
Complex::Complex()
{
Real = 0;
Imaginary = 0;
}
Complex::Complex(double r, double i)
{
Real = r;
Imaginary = i;
}
Operator Overloading
Complex Complex::operator+(Complex a)
{
Complex t;
[Link] = Real + [Link];
[Link] = Imaginary + [Link];
return t;
}
void Complex::Print()
{
cout << Real << endl;
cout << Imaginary << endl;
}
int main(void)
{
Complex A(1,1), B(2,3);
Complex C;
C = A + B;
[Link]();
return 0;
}