Scope
Resolution Operator : ‘::’ is known as Scope Resolution Operator. Different
program modules are written in various blocks. Same variable name can be used
in different blocks. Scope of a variable extends from the point of declaration
to the end of the block. A variable declared inside a block is ‘local’
variable. scope resolution operator is used to define the member function
outside the class. It is also used to print the value of global variable and
local variable It comes in two forms:
::Num - unary
operator – refers to external scope)
TestClass::Num
Its unary form is used to access
a name that has external scope and has been hidden by local or class scope.
class TestClass
{
private
:: //Declaration Private Data Member
public:
void
GetData(); //Member Method
};
/* The Member Method using Scope
Resolution operator.*/
void TestClass::GetData() // GetData()
{
}
Example of Scope Resolution Operator.
#include<iostream.h>
#include <conio.h>
class
test
{
private:
int
num;
public:
test()
{
num=20;
}
void disp()
{
int num=5;
cout<<"\n\tDisplaying
the value of global variable "<< test::num;
cout<<"\n\tDisplaying
the value of local variable "<< num;
}
};
void main()
{
test t;
t.disp();
}
Example - Find the Sum Series - //sum
of series : x+x^2/2!+x^3/3! ... + x^n/n!
#include<iostream.h>
#include <conio.h>
class
sumseries
{
private:
int
x,n;
float
sum;
public:
void
accept();
void
displaysum();
int
fact(int);
double
term(int,int);
sumseries();
};
sumseries::sumseries()
{
sum=1.0;
}
void
sumseries::accept()
{
cout<<"\n\tEnter
value of N :";
cin>>n;
cout<<"\n\tEnter value of
X :";
cin>>x;
}
int
sumseries::fact(int n)
{
int f=1,i;
for(i=1;i<=n;i++)
{
f=f*i;
}
return(f);
}
double
sumseries::term(int p,int q)
{
int j;
float y=1;
for(j=1;j<=q;j++)
{
y=y*p;
}
return
y;
}
void
sumseries::displaysum()
{
int i;
for(i=1;i<=n;i++)
{
if(i<n)
cout<<x<<"
^ "<<i<<" / "<<i<<"!
"<<"+ ";
else
cout<<x<<"
^ "<<i<<" / "<<i<<"!
";
sum=sum+(term(x,i)/fact(i));
}
cout<<"
= "<<sum<<"\n";
}
void
main()
{
clrscr();
sumseries
s;
s.accept();
s.displaysum();
getch();
}
No comments:
Post a Comment