简体   繁体   English

将常量传递给C ++构造函数

[英]Passing constant to C++ constructor

I have a class where the constructor receives an integer: 我有一个构造函数接收整数的类:

class One
{
public:
    One(int i)
    {
        foo(i);
    }

    void foo(int i)
    {
        // Do something with i
    }
};

The above compiles fine. 上面的编译很好。

I have a second class that has a member of type One. 我有一个第二类有一个类型的成员。 Compiling this results in an error where I pass the int (the error is "expected a type specifier"): 编译这会导致我传递int的错误(错误是“期望的类型说明符”):

class Two
{
public:
    One x(1);
};

I can, however, initialize the member if it is a pointer: 但是,如果它是一个指针,我可以初始化该成员:

class Three
{
public:
    One *x = new One(1);
};

Can I initialize the class without using a pointer? 我可以在不使用指针的情况下初始化类吗?

Thanks! 谢谢!

With: 附:

class Two
{
public:
    One x(1);
};

and based on language rules, the compiler attempts to parse x as a member function returning an object of type One , but rather than seeing valid parameter-declarations which requires at least a list of 0 or more type-specifier s, it sees a non-type . 并且基于语言规则,编译器尝试将x解析为返回类型为One的对象的成员函数,但不是看到至少需要0个或更多类型说明符的列表的有效参数声明 ,而是看到非型

 class Three { public: One *x = new One(1); }; 

Can I initialize the class without using a pointer? 我可以在不使用指针的情况下初始化类吗?

Yes, use the uniform-brace-initialization syntax for value-initialization : 是的,使用uniform-b​​race-initialization语法进行值初始化

class Three
{
public:
    One x{1};
};

Or copy-initialization : 或者复制初始化

class Three
{
public:
    One x = 1;  //Uses converting constructor, 
    //see http://en.cppreference.com/w/cpp/language/converting_constructor

    //or
    One x = One(your, multiple, arguments, here);
};

Or member-initializer-lists in the Constructor: 或构造函数中的member-initializer-lists

class Three
{
public:
    Three(...) : x(1) { ... }
    One x;
    ...
};
One x(1);

is parsed as a function declaration, that is why it expects a type in parentheses. 被解析为函数声明,这就是它期望括号中的类型的原因。 You can use 您可以使用

One x = 1;

or 要么

One x{1};

instead. 代替。

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

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