简体   繁体   English

如何在C ++中正确初始化Struct

[英]How to correctly initialize a Struct in c++

Currently running into an issue with this question in my homework. 目前在我的作业中遇到这个问题。 I believe that only 4,7 are incorrect (In Visual Studio they don't throw an error). 我相信只有4,7不正确(在Visual Studio中,它们不会引发错误)。 But i'm honestly not sure why they are the only ones. 但老实说,我不确定为什么他们是唯一的。 Since 3 works, I assumed they would work as well but that seems to not be the case. 由于3作品,我以为他们也将工作,但事实并非如此。 Any advice? 有什么建议吗?

struct A {
    double x;
    A(double x = 1) : x(x) { }
};

struct B {
    double x;
    B(A a = 2.0) : x(a.x) { }
};

struct C {
    double x;
    C(B b = B(3)) : x(b.x) { }
};

int main() {
    A a; // (1)
    A a = 4; // (2)
    B b; // (3)
    B b = 5; // (4)
    B b(a); // (5) (a is an object of class A)
    C c; // (6)
    C c = 6.0; // (7)
    C c(a); // (8) (a is an object of class A)
    C c(b); // (9) (b is an object of class B)
}

Correct ones are: 正确的是:

a) 1-3 a)1-3

b) 1-3,5,9 b)1-3,5,9

c) 1-6,8,9 c)1-6、8、9

d) 1-7 d)1-7

e) 1-3,5,6,9 e)1-3,5,6,9

f) none f)没有

My reasoning: 我的推理:

1) Correct, just default constructor 1)正确,只是默认构造函数

2)Correct, constructor default or value (4) 2)更正,构造函数默认值或值(4)

3) Correct, default constructor 3)正确的默认构造函数

4) Incorrect, No constructor for an int 4)不正确,没有用于int的构造函数

5) Correct, exists constructor for object of type A 5)正确,存在类型A的对象的构造函数

6) Correct, Default 6)正确,默认

7)Incorrect, same as 4 7)不正确,与4相同

8) This one i'm not sure on, there is no constructor for objects of type A, so I would say incorrect 8)我不确定这一点,没有A类型对象的构造函数,所以我会说不正确

9) Correct, constructor exists. 9)正确,构造函数存在。

This is my reasoning in any case, but i'm not sure where i'm going wrong. 无论如何,这都是我的理由,但我不确定我要去哪里。

The rule is, when converting from a type to another (here from/to int , double , A , B or C ): only one user-provided conversion can be used . 规则是,当从一种类型转换为另一种类型(此处为from / to intdoubleABC )时: 只能使用一个用户提供的转换

This makes indeed B b = 5; // (4) 这确实使B b = 5; // (4) B b = 5; // (4) invalid since 5 (an int ) needs to be: B b = 5; // (4)无效,因为5int )必须为:

  • converted to double (first standart-conversion ), 转换为double (第一个标准转换 ),
  • then to a A (first user-defined conversion ), 然后转到A (首次用户定义的转换 ),
  • then to a B (second user-defined conversion ). 然后转到B (第二个用户定义的转换 )。

That last one breaks the rule, and this conversion sequence is not legal. 最后一个违反规则,此转换顺序不合法。

I'm honestly not sure why they are [ incorrect ]. 老实说,我不确定他们为什么[不正确]。

You can use this rule to check other expressions. 您可以使用此规则检查其他表达式。


Finally, you can impress your teacher with std::is_convertible : 最后,您可以使用std::is_convertible打动您的老师:

std::is_convertible_v<B, C> returns true iff B is convertible to C ( demo ). 如果B可转换为Cdemostd::is_convertible_v<B, C>返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM