fork download
  1. #include <iostream>
  2. #include <utility>
  3. #include <cstring>
  4.  
  5. class S {
  6. public:
  7. S(const char* s) : l(std::strlen(s)), s(new char[l+1]) { std::strcpy(this->s, s); }
  8. S(const S& o) : l(o.l), s(new char[l+1]) { strcpy(s, o.s); }
  9. S& operator = (S o)
  10. {
  11. swap(o);
  12. return *this;
  13. }
  14. ~S() { delete [] s; }
  15. void swap(S& o)
  16. {
  17. using std::swap;
  18. swap(l, o.l);
  19. swap(s, o.s);
  20. }
  21. friend std::ostream& operator << (std::ostream& os, const S& s) { return os << s.s; }
  22. private:
  23. size_t l;
  24. char* s;
  25. };
  26.  
  27. class A {
  28. public:
  29. A(const char* s) : s(s) {}
  30. A(const A& o) : s(o.s) {}
  31. A& operator = (A o)
  32. {
  33. swap(o);
  34. return *this;
  35. }
  36. virtual ~A() {}
  37. void swap(A& o)
  38. {
  39. s.swap(o.s);
  40. }
  41. friend std::ostream& operator << (std::ostream& os, const A& a) { return os << a.s; }
  42.  
  43. private:
  44. S s;
  45. };
  46.  
  47. template <int N>
  48. class B : public virtual A {
  49. public:
  50. B(const char* sA, const char* s) : A(sA), s(s) {}
  51. B(const B& o) : A(o), s(o.s) {}
  52. B& operator = (B o)
  53. {
  54. swap(o);
  55. return *this;
  56. }
  57. virtual ~B() {}
  58. void swap(B& o)
  59. {
  60. A::swap(o);
  61. s.swap(o.s);
  62. }
  63. friend std::ostream& operator << (std::ostream& os, const B& b)
  64. { return os << (const A&)b << ',' << b.s; }
  65.  
  66. private:
  67. S s;
  68. };
  69.  
  70. class D : public B<1>, public B<2> {
  71. public:
  72. D(const char* sA, const char* sB1, const char* sB2, const char* s)
  73. : A(sA), B<1>(sA, sB1), B<2>(sA, sB2), s(s)
  74. {}
  75. D(const D& o) : A(o), B<1>(o), B<2>(o), s(o.s) {}
  76. D& operator = (D o)
  77. {
  78. swap(o);
  79. return *this;
  80. }
  81. virtual ~D() {}
  82. void swap(D& o)
  83. {
  84. B<1>::swap(o); // calls A::swap(o); A::s changed to o.s
  85. B<2>::swap(o); // calls A::swap(o); A::s returned to original value...
  86. s.swap(o.s);
  87. }
  88. friend std::ostream& operator << (std::ostream& os, const D& d)
  89. {
  90. // prints A::s twice...
  91. return os
  92. << (const B<1>&)d << ','
  93. << (const B<2>&)d << ','
  94. << d.s;
  95. }
  96. private:
  97. S s;
  98. };
  99.  
  100. int main() {
  101. D x("ax", "b1x", "b2x", "x");
  102. D y("ay", "b1y", "b2y", "y");
  103. std::cout << x << "\n" << y << "\n";
  104. x = y;
  105. std::cout << x << "\n" << y << "\n";
  106. }
  107.  
  108.  
Success #stdin #stdout 0s 3068KB
stdin
Standard input is empty
stdout
ax,b1x,ax,b2x,x
ay,b1y,ay,b2y,y
ax,b1y,ax,b2y,y
ay,b1y,ay,b2y,y