Вы находитесь на странице: 1из 5

ENG.

ELHAM ABDULRAHMAN C++ LAB – MECHATRONICS – LEVEL 3

Practicing is the only way to understand programming language.

Headlines:

1- inline function.
2- getline function.
3- Initializer list.
4- Getters and setters.
5- Scope resolution operator.
6- Exercises.
7- Homework.

Inline function

#include <iostream>
using namespace std;
class In {
public:
inline void dis(int x)
{
cout<<x<<endl;
}
}; // End of class In
int main( )
{ In i ;
i.dis(10);
return 0;
} // End of main function
2018-2019 Page 1 of 5
ENG. ELHAM ABDULRAHMAN C++ LAB – MECHATRONICS – LEVEL 3

getline function

#include <iostream>
#include<string>
using namespace std;
class Student {
public:
void display(string n)
{ name = n;
cout<<"The name is "<<n<<endl;
}
private:
string name;
}; // End of class Student
int main( )
{
cout<<"Enter your name, please:"<<endl;
string s;
cin>>s;
Student obj;
obj.display(s);
return 0;
} // End of main function

What will happen if we replace


cin>>s; with getline(cin,s);

2018-2019 Page 2 of 5
ENG. ELHAM ABDULRAHMAN C++ LAB – MECHATRONICS – LEVEL 3

Initializer list

int main( )
{ cout<<"Enter your name, please:"<<endl;
string in;
getline(cin,in);
Student s(in);
Modifying the main function
return 0;
is not allowed.
} // End of main function

Write a class that contains a private string variable


and function to print the name of the student.

#include <iostream>
#include<string>
using namespace std;
class Student {
public:
Student ( string n="Aya") : name(n)
{ display( ); }
private:
string name;
void display( )
{ cout<<"The name is "<<name<<endl; }
}; // End of class Student
int main( )
{
cout<<"Enter your name, please:"<<endl;
string in;
getline(cin,in);
Student s(in);
Student s2;
return 0;
} // End of main function

2018-2019 Page 3 of 5
ENG. ELHAM ABDULRAHMAN C++ LAB – MECHATRONICS – LEVEL 3

In some cases, initializer list must be used.

Getters and Setters

#include <iostream>
using namespace std;
class Test {
public:
void setnum(int n1, int n2)
{ num1 = n1;
num2 = n2;
calc( );
}
int getsum( ){ return sum ; }
double getdiv( ){ return div; }
private:
int num1,num2;
int sum;
double div;
void calc( )
{ sum = num1 + num2;
div = (double)num1/num2; }
}; // End of class Test
int main( )
{ cout<<"Enter two numbers, please:"<<endl;
int a,b;
cin>>a>>b;
Test t ;
t.setnum(a,b);
cout<<"The summation is: "<<t.getsum()<<endl;
cout<<"The division is: "<<t.getdiv()<<endl;
return 0;
} // End of main function

2018-2019 Page 4 of 5
ENG. ELHAM ABDULRAHMAN C++ LAB – MECHATRONICS – LEVEL 3

Scope resolution operator ::

#include <iostream>
using namespace std;
class Try {
public:
void display( );
}; // End of class Try
void Try::display(){ cout<<"Lab 3"<<endl; }
int main( )
{ Try a ;
a.display();
return 0;
} // End of main function

Exercises

Homework

Will be taken in
the lab

2018-2019 Page 5 of 5

Вам также может понравиться