Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

1.

Design a class for Fractional numbers that supports following operators on its objects a) + (Adds to Fractions) b) (Subtracts a fraction from another) c) << (prints the fraction in a/b form) d) >> (Takes data from user) e) Postfix ++ f) Prefix ++ g) += h) Unary 2. Implement bubble sort as template. 3.

Run and analyze the output of following programs.

a) #include<iostream> using namespace std; template <class t> void mySwap(t &var1, t &var2) { t temp; temp= var1; var1 = var2; var2 = temp; } int main() { char firstchar,secondchar; int firstint,secondint; float firstfloat,secondfloat; cout << "enter two characters"; cin >> firstchar >> secondchar; mySwap(firstchar,secondchar);

cout << firstchar << " " << secondchar << endl; cout << "enter two integers" ; cin >> firstint >> secondint; mySwap(firstint,secondint); cout << firstint<< " " <<secondint<<endl; cout <<"enter two floating point numbers"; cin >> firstfloat>>secondfloat; mySwap(firstfloat,secondfloat); cout << firstfloat <<" "<<secondfloat<<endl; return 0; }

b) #include<iostream> using namespace std; template<class T, class U = char> class A { public: T x; U y; }; int main() { A<char> a; A<int, int> b; cout<<sizeof(a)<<endl; cout<<sizeof(b)<<endl; return 0; }

c) #include<iostream> using namespace std; template<class T = char, class U, class V = int>

class A { // members of A }; int main() { } d) #include<iostream> using namespace std; template <class T, int max> int fun(T a) { cout<<a<<endl; cout<<max; } int main() { int x = 30; fun<int, 100>(23); } e) template <class T, int element> int fun(T a) { } int main() { int x = 30; fun<int, x>(23); } f) #include<iostream> using namespace std;

template <class T> class MyClass { static int count; public: void f() { ++count; } int getCount() {return count;} }; template <class T> int MyClass<T>::count = 0; int main(int argc, char* argv[]) { MyClass<int> a; MyClass<char> b; a.f(); cout<<a.getCount()<<endl; cout<<b.getCount(); return 0; }

g) #include<iostream> using namespace std; int myMax(int x, int y) { cout << "int max(int, int) called" << endl; return x > y? x : y; } template <class T> T myMax(T x, T y) { cout << "T max<?>(T, T) called" << endl; return x > y? x : y;

} int main() { int x = 20, y = 30; cout << myMax(x, y) << endl; cout << myMax<char>('x', 'y') << endl; cout << myMax<int>(x, y) <<endl; return 0; }

You might also like