Aid needed
I want to know why the print function displays val1 and val2 wrongly
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
using namespace std;
template <class>
void print();
template <class T>
class test
{
private:
T val1,val2;
public:
test(T a,T b)
{
val1=a;
val2=b;
}
test(){}
T lowest();
template <class>
friend void print();
};
template <class T>
T test<T>::lowest()
{
T temp=val1<val2 ? val1 : val2;
cout<<"\n\nLowest number: "<<temp;
}
template <class T2>
void print()
{
test<T2> temp;
cout<<"\nval1 = "<<temp.val1;
cout<<"\nval2 = "<<temp.val2;
}
int main()
{
double x,y;
cout<<"Enter a number: ";
cin>>x;
cout<<"Enter another number: ";
cin>>y;
test<double> obj1(x,y);
print<double>();
obj1.lowest();
cin.ignore();
cin.get();
}
|
1 2 3 4 5 6 7 8
|
template <class T2>
void print()
{
test<T2> temp; // ?
cout<<"\nval1 = "<<temp.val1;
cout<<"\nval2 = "<<temp.val2;
}
|
because temp is not related to object obj1 you have in main
regards
-dean
Try passing the object to the print function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
template <class T2>
void print(test<T2> temp) //define temp as argument here
{
cout<<"\nval1 = "<<temp.val1;
cout<<"\nval2 = "<<temp.val2;
}
//...
int main()
{
double x,y;
cout<<"Enter a number: ";
cin>>x;
cout<<"Enter another number: ";
cin>>y;
test<double> obj1(x,y);
print<double>(obj1); //pass it here
obj1.lowest();
cin.ignore();
cin.get();
}
|
Hope that helps.
All the best,
NwN
Last edited on
Thank you all. It's working perfectly!!!
Topic archived. No new replies allowed.