gpt4 book ai didi

c++ - 声明引用在类中有效,但在主函数中无效

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:30 25 4
gpt4 key购买 nike

class Test{
int &b; // no error, can compile
};


int main() {
int &b; // error: 'b' declared as reference but not initialized
}

为什么我不能在 main 函数中使用 int &b,但可以在 Test 类中使用?

最佳答案

引用必须绑定(bind)到它开始存在的地方。

在类中,声明指定类的每个实例都应具有此引用。每个此类引用在创建其类实例时就开始存在。此时,类中的某些构造函数必须通过构造函数的成员初始化列表对其进行初始化,前提是引用尚未在声明中初始化(而您的未初始化)。

在函数中,引用在执行通过声明时开始存在。因此必须在此时对其进行初始化。

关于c++ - 声明引用在类中有效,但在主函数中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com