我正在阅读 Stroustrup 的 TCPPPL。书中的一个练习有点像这样:
struct X{
int i;
X(int);
X operator+(int);
};
struct Y{
int i;
Y(X);
Y operator+(X);
operator int();
};
extern X operator* (X,Y);
extern int f(X);
X x=1;
Y y=x;
int i=2;
int main()
{
//main body
}
我的问题(也许是一个微不足道的问题)是行中发生的事情:X x =1;? struct X 类型的变量 x 是否被初始化,即它的 i 被赋予值 1?如果是这样,为什么 1 周围没有花括号?
最佳答案
My question (maybe a trivial one) is that what is happening in the line: X x =1;
X 定义了一个接受一个 int 的构造函数:X::X(int i)
声明:
X x = 1;
相当于:
X x = X(1);
或
auto x = X(1);
或
auto x = X { 1 };
即使用 (int) 构造函数构造 X。
i.e. its i is being given the value 1?
是的,没错**。
** 或至少这是我的假设,没有看到构造函数的定义。我假设它看起来像这样:
X::X(int arg)
: i(arg)
{
}
关于c++ - 如何在 C++ 中初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49169172/