fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. template <typename T> class B; //forward declare
  6.  
  7. template <typename T>
  8. class A
  9. {
  10. T valuea;
  11. public:
  12. A(){};
  13. T getValuea()
  14. {
  15. return valuea;
  16. }
  17.  
  18. void setValuea(T x)
  19. {
  20. valuea = x;
  21. }
  22. A(const A &x)
  23. {
  24. valuea = x.valuea;
  25. }
  26.  
  27. friend class B<T>; //A<int> is a friend of B<int>
  28. };
  29.  
  30. template <typename T>
  31. class B : A<T>
  32. {
  33. T valueb;
  34. public:
  35. using A<T>::setValuea;
  36. using A<T>::getValuea;
  37. B(){};
  38. T getValueb()
  39. {
  40. return valueb;
  41. }
  42. void setValueb(T x)
  43. {
  44. valueb = x;
  45. }
  46. B(const B &x)
  47. {
  48. valueb = x.valueb;
  49. this->valuea = x.valuea;
  50. }
  51. };
  52.  
  53. struct Date
  54. {
  55. int day;
  56. int month;
  57. int year;
  58.  
  59. friend ostream& operator << (ostream& os, const Date& date)
  60. {
  61. return os << "Day: " << date.day << ", Month: " << date.month << ", Year: " << date.year << " ";
  62. }
  63. };
  64.  
  65. int main()
  66. {
  67. B<float> b;
  68. b.setValuea(1.34);
  69. b.setValueb(3.14);
  70.  
  71. cout << "b.setValuea(1.34): " << b.getValuea() << endl
  72. << "b.setValueb(3.14): " << b.getValueb() << endl;
  73.  
  74. B<int> a;
  75. a.setValuea(1);
  76. a.setValueb(3);
  77.  
  78. cout << "a.setValuea(1): " << a.getValuea() << endl
  79. << "a.setValueb(3): " << a.getValueb() << endl;
  80.  
  81. B<char> y;
  82. y.setValuea('a');
  83. y.setValueb('c');
  84.  
  85. cout << "y.setValuea('a'): " << y.getValuea() << endl
  86. << "y.setValueb('c'): " << y.getValueb() << endl;
  87.  
  88. B<string> u;
  89. u.setValuea("good");
  90. u.setValueb("morning");
  91.  
  92. cout << "u.setValuea(good): " << u.getValuea() << endl
  93. << "u.setValueb(morning): " << u.getValueb() << endl;
  94.  
  95. B<Date> p;
  96. p.setValuea({ 27, 10, 2014 });
  97. p.setValueb({ 2, 11, 2014 });
  98.  
  99. cout << "p.setValuea({ 27, 10, 2014 }): " << p.getValuea() << endl
  100. << "p.setValueb({ 2, 11, 2014 }): " << p.getValueb() << endl;
  101.  
  102.  
  103. system("Pause");
  104. return 0;
  105. }
  106.  
  107.  
Success #stdin #stdout #stderr 0s 3476KB
stdin
Standard input is empty
stdout
b.setValuea(1.34): 1.34
b.setValueb(3.14): 3.14
a.setValuea(1): 1
a.setValueb(3): 3
y.setValuea('a'): a
y.setValueb('c'): c
u.setValuea(good): good
u.setValueb(morning): morning
p.setValuea({ 27, 10, 2014 }): Day: 27, Month: 10, Year: 2014 
p.setValueb({ 2, 11, 2014 }):  Day: 2, Month: 11, Year: 2014 
stderr
sh: Pause: not found