samedi 11 septembre 2021

A C++ problem that has troubled me for a long time

#include <iostream>
#include <vector>
//define class C
class C {
 public:
  C() = default;
  ~C() = default;

  double x() { return x_; }

  void set_x(double x) { x_ = x; }

  double y() { return y_; }

  void set_y(double y) { y_ = y; }

 protected:
  double x_;
  double y_;
};

//define class B
class B {
 public:
  B() = default;
  ~B() = default;

  void set_c(std::vector<C> c) { c_ = c; }

  std::vector<C> c() { return c_; }

  std::vector<C> *mutable_c() { return &c_; }

 protected:
  std::vector<C> c_;
};

//define class A
class A {
 public:
  A() = default;
  ~A() = default;

  B b() { return b_; }

  void set_b(B b) { b_ = b; }

 protected:
  B b_;
};

int main() {
  A a;
  B b;
  C c1, c2;
  std::vector<C> c;
  c1.set_x(11.11);
  c1.set_y(22.22);
  c.push_back(c1);
  c2.set_x(33.33);
  c2.set_y(44.44);
  c.push_back(c2);
  b.set_c(c);
  a.set_b(b);

 //get value
  for (auto it : *(a.b().mutable_c())) {
    std::cout << "111:" << it.x() << std::endl;
    std::cout << "222:" << it.y() << std::endl;
  }

  std::cout<<std::endl;

   //get value
    for (auto it : a.b().c()) {
    std::cout << "333:" << it.x() << std::endl
    std::cout << "444:" << it.y() << std::endl;
  }
  return 1;
}

results in the error stated in the title. I do realize that if I create a variable in class A and instanciate it there and return it directly, the error will vanish.

But, here I want to understand what is the meaning of this error and why can't I use it this way.

//wrong

111:0

//wrong

222:4.64953e-310

111:33.33

222:44.44

333:11.11

444:22.22

333:33.33

444:44.44

Aucun commentaire:

Enregistrer un commentaire