如何在C ++中初始化结构

问题描述 投票:0回答:1

我正在阅读Stroustrup的TCPL。书中的练习有点像这样:

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,即它的值是否为1?如果是这样,为什么1周围没有花括号?

c++ structure
1个回答
1
投票

我的问题(也许是一个微不足道的问题)是行中发生的事情: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.

即它的值是1吗?

对,那是正确的**。

**或者至少这是我的假设,没有看到构造函数的定义。我假设它看起来像这样:

X::X(int arg)
: i(arg)
{
}
© www.soinside.com 2019 - 2024. All rights reserved.