HarmonyOS 鸿蒙Next 'this' is not allowed to be accessed before all member variables are initialized

HarmonyOS 鸿蒙Next ‘this’ is not allowed to be accessed before all member variables are initialized

class A { let b: B

public init() {
    b = B(this)
}

}

class B { let a: A

public init() {
    this.a = a
}

}

这种方式在其他语言是可以的,在仓颉不允许。要如何解决?

3 回复

用箭头函数呢?

更多关于HarmonyOS 鸿蒙Next 'this' is not allowed to be accessed before all member variables are initialized的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


请教一下,怎么用?

在HarmonyOS鸿蒙Next中,'this' is not allowed to be accessed before all member variables are initialized 错误通常发生在类的构造函数中,试图在成员变量完全初始化之前访问 this 指针。鸿蒙Next的编译器遵循严格的初始化顺序规则,确保所有成员变量在构造函数体执行之前已经初始化完毕。

具体来说,当你在构造函数的初始化列表中使用 this 指针时,编译器会检查所有成员变量是否已经初始化。如果某个成员变量尚未初始化,编译器会抛出此错误。例如:

class MyClass {
public:
    MyClass(int x) : member(x), anotherMember(this->member) {
        // 构造函数体
    }

private:
    int member;
    int anotherMember;
};

在上面的代码中,anotherMember 试图在构造函数初始化列表中使用 this->member,但此时 member 尚未完全初始化,导致编译错误。

要解决这个问题,确保在访问 this 指针之前,所有成员变量已经初始化。可以通过调整初始化顺序或避免在初始化列表中使用 this 指针来实现。例如:

class MyClass {
public:
    MyClass(int x) : member(x) {
        anotherMember = member; // 在构造函数体中初始化
    }

private:
    int member;
    int anotherMember;
};

通过这种方式,可以避免在初始化列表中使用 this 指针,从而消除编译错误。

回到顶部