Lecture20
Lecture20
Puru
with
CS101 TAs and Staff
• Member functions
− New feature introduced in C++
− Actions/operations that effect the entity
struct Point{
double x,y;
};
struct Disk{
Point center; // contains Point
double radius;
};
Disk d;
d.radius = 10;
d.center = {15, 20};
// sets the x {member of center member of d
struct Queue{
int elements[N], nwaiting,front;
bool insert(int v){
…
}
• Why useful?
};
~Queue(){ //Destructor
if(nWaiting>0) cout << “Warning:”
<<“ non-empty queue being destroyed.”
<< endl;
}
};
int main(){
V3 u(1,2,3), a(4,5,6), s;
double t=10;
s = u*t + a*t*t*0.5;
cout << s.x <<‘ ‘<< s.y << ‘ ‘<< s.z << endl;
}
• dptr = &d1;
• (*dptr).radius = 5; //changes the radius of d1
• Operator ->
– (*x).y is same as x->y
• dptr->radius = 5; // same effect as above
struct Disk2{
double radius;
Point *centerptr;
}
Point p={10,20};
Disk2 d;
d.centerptr = &p;
cout << d.centerptr->x << endl; // will print 10.
• Within the body of a member function, the keyword this points to the receiver
i.e., the struct on which the member function has been invoked.
struct V3{
double x, y, z;
double length(){
return sqrt(this->x * this->x
+ this->y * this->y
+ this->z * this->z);
}
}
};
// only the relevant elements are copied
public:
Queue(){ … }
bool insert(int v){
..
}
bool remove(int &v){
..
}
};
class Queue{
int elements[N], nWaiting, front;
public:
Queue(){…}
bool remove(int &v){…}
bool insert(int v){…}
};
• Now you can read from that file by invoking the >> operator!
ofstream outfile(“f2.txt”);
// constructor call. Object outfile is created and associated
// with f2.txt, which will get created in the current directory
repeat(10){
int v;
infile >> v;
outfile << v;
}
// f1.txt must begin with 10 numbers. These will be read and
// written to file f2.txt
}
while (true) {
ans += base/fac;
base *= x;
fac *= (++ix);
if (base/fac < epsilon) {
break; Terminates
} immediately
cout << (base/fac) << endl;enclosing
while loop
}
CS101 Autumn 2019 @ CSE IIT Bombay 54