在班级内部初始化班级 [英] Initializing class inside class

查看:76
本文介绍了在班级内部初始化班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我的问题也许很简单,但是我找不到解决方案。

I am new to C++, and my question might be trivial, but I wasn't able to find a solution.

我有两个类, S L S 看起来像这样:

I have two classes, S and L. S looks like this:

class S
{
private:
    int m_x;

public:
    S(int x) : m_x(x)
    {
    }

    int m_y = 2*m_x;   // some random action in S
};

现在我有第二类 L ,我要在其中初始化 S 对象的地方:

Now I have a second class L, where I want to initialize an S-object:

class L
{
private:
    S s(10);   // 10 is just some random value
    int m_y;
public:
    L(int y): m_y(y)
    {
    }

// ignore the rest for now.
};

这会产生错误错误:数字常量之前的预期标识符 s(10)的初始化行。

This produces an error error: expected identifier before numeric constant at the line of initialization of s(10).

我不明白为什么我不能这样做。我该如何解决?如果我想初始化对象 S s(m_y)怎么办?

I don't understand why I can't do that. How could I fix this? What if I wanted to initialize the object S s(m_y) instead?

推荐答案

您可以使用成员初始值设定项列表,就像对 m_y

L(int y): s(10), m_y(y)
{
}

或使用 C ++ 11中的默认初始值设定项列表,但请注意,仅支持大括号或等于初始值设定项,不支持

Or use default initializer list from C++11, but note it's only supported for brace or equals initializer, not including the parenthesis one.

class L
{
private:
    S s{10};   // or S s = S(10);
    int m_y;
public:
    L(int y): m_y(y) // s is initialized via default initializer list
                     // m_y is initialized via member initializer list
    {
    }
};

这篇关于在班级内部初始化班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆