Chapter7_Class_and_Objects_part2
Chapter7_Class_and_Objects_part2
© HĐC 2024.1
Content
User requirements:
Simple declaration as basic data types
Safe to use, users do not have to call functions to allocate and
deallocate memory
Example of usages:
Vector v1; // v1 has 0 elements
Vector v2(5,0); // v2 has 5 elements init. with 0
Vector v3=v2; // v3 is a copy of v2
Vector v4(v3); // the same as above
Vector f(Vector b) {
double a[] = {1, 2, 3, 4};
Vector v(4, a);
...
return v;
}
// Do not care about memory management
class X {
int a, b;
(1) Pass argument with
public:
value and copy
X() : a(0), b(0) {}
X(X x); // (1) (2) As (1)
X(const X x); // (2)
? (3) Not copy the argument,
X(X& x); // (3)
X(const X& x); // (4) however x can be changed
... unintendedly inside the
function
};
void main() { (4) Not copy the argument,
X x1; safe for the origin
X x2(x1); correct syntax!
...
}
In this case 0 0 0 0 0
Vector::Vector(constVector& a) { //(4)
create(a.nelem);
for (int i=0; i < nelem; ++i)
data[i] = a.data[i];
}
class Complex {
double re, im;
public:
Complex(double r = 0, double i =0): re(r),im(i) {}
double real() const { return re; }
double imag() const { return im; }
Complex operator+(const Complex& b) const {
Complex z(re+b.re, im+b.im);
return z;
}
Complex operator-(const Complex& b) const {
return Complex(re-b.re, im-b.im);
}
Complex operator*(const Complex&) const;
Complex operator/(const Complex&) const;
Complex& operator +=(const Complex&);
Complex& operator -=(const Complex&);
...
};
#include “mycomplex.h”
Complex Complex::operator*(const Complex& b) const {
...// left for exercise!
}
Complex Complex::operator/(const Complex& b) const {
...// left for exercise!}
Complex&Complex::operator+=(const Complex& b) {
re += b.re; im+= b.im;
return *this;
}
Complex& operator -=(const Complex&) { ... }