gpt4 book ai didi

c++ - 声明为类字段而不是全局变量

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

看看这个非常基本的 C++ 代码:

class Class1 {

};

Class1 c1;

class Class2
{
public:
Class2(Class1 &c)
{

}
};

// Class2 abcd(c1); // OK outside declaration

class Class3
{
public:
Class2 abcd(c1); // Declaration of abcd as field -> error: unknown type name 'c1'
};

关于 abcd 声明,我有一些不明白的地方:如果我将它声明为全局变量,它就可以工作。但是,如果我将其声明为 Class3 中的字段,则会出现编译器错误。

最佳答案

default member initializer (C++11 起)非静态数据成员 只能与大括号或等号初始化器一起使用,但不能与圆括号初始化器一起使用。

Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.

所以你可以

class Class3
{
public:
Class2 abcd{c1}; // brace initializer
Class2 abcd = Class2(c1); // equals initializer
};

关于c++ - 声明为类字段而不是全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57782043/

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