fork download
  1. //g++ 7.4.0
  2.  
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. struct A
  9. {
  10. int value;
  11. A()
  12. {
  13. cout << "A created: " << this << endl;
  14. }
  15.  
  16. ~A()
  17. {
  18. cout << "A deleted: " << this << endl;
  19. }
  20.  
  21. void print()
  22. {
  23. cout << this << endl;
  24. }
  25. };
  26.  
  27. struct B
  28. {
  29. A item;
  30. B()
  31. {
  32. cout << "B created: " << this << endl;
  33. }
  34.  
  35. ~B()
  36. {
  37. cout << "B deleted: " << this << endl;
  38. }
  39.  
  40. void print()
  41. {
  42. cout << this << endl;
  43. }
  44. };
  45.  
  46. int main()
  47. {
  48. vector<B*> items;
  49. {
  50. B item;
  51. item.item.value = 33;
  52. items.push_back(&item);
  53. cout << "1" << endl;
  54. }
  55. cout << "2" << endl;
  56. // вопрос первый
  57. items[0]->print(); // адрес тот же
  58. // вопрос второй
  59. items[0]->item.print(); // такой же адрес как и у родителя
  60. // объект всё ещё работает
  61. cout << items[0]->item.value << endl;
  62. // можно присваивать значения
  63. items[0]->item.value = 44;
  64. // значения присваиваются
  65. cout << items[0]->item.value << endl;
  66. }
Success #stdin #stdout 0s 5432KB
stdin
Standard input is empty
stdout
A created: 0x7ffd0b1888b4
B created: 0x7ffd0b1888b4
1
B deleted: 0x7ffd0b1888b4
A deleted: 0x7ffd0b1888b4
2
0x7ffd0b1888b4
0x7ffd0b1888b4
33
44