将堆栈对象等同于对象 C++ 中的另一个对象

Equate stack object to another inside an object C++

我有两个对象,调用 AB 例如

class A {
   private:
     int x; 
     int y;

   public:
     A();
     A(int x, int y);
     void setX(int);
     void setY(int);
};

class B {
   private:
     const A a1;

   public:
     B();
     B(int x, int y) {
       //my problem is here
       A a(x, y);
       this->a1 = a;
     };
};

如果 B 是用参数初始化的,我想用参数初始化 a1 以及 B 是用参数初始化的,因此 A(int x, int y).

我不想 a1 在堆中初始化。

我目前收到此错误

no operator "=" matches these operands -- operand types are: const Brain = Brain

修改

来自@songyuanyao 的回答

B::B(int x, int y) : a1(x, y){};

它有效,但由于我对 const 缺乏了解,我现在遇到了一个不同的问题。当我像这样从 A(int x, int y) 调用 setXsetY

A::A(int x, int y) {
    setX(x);
    setY(y);
}

void A::setX(int x) {
    this->x = x;
}

void A::setY(int y) {
    this->y = y;
}

它似乎没有改变 class Axy values/attributes。

您应该用 member initializer list 初始化 const 数据成员。作为const对象,可以初始化,但不能赋值;所以 this->a1 = a; 不起作用。

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

例如

B(int x, int y) : a1(x, y) {}