【问题标题】:Passing arguments to the class constructor in a declaration of another class在另一个类的声明中将参数传递给类构造函数
【发布时间】:2011-10-12 00:44:16
【问题描述】:

我有这样的东西:

#include <iostream>
using namespace std;

class FirstClass
{
    public:
        FirstClass(int _vx) : vx(_vx) {}
        int x () {return vx;}
    private:
        int vx;
};

很明显,我必须写:

int main ()
{
    FirstClass Object1(666);
    cout << Object1.x();
    return 0;
}

一切正常。但问题是,当我想在另一个类中使用它时:

#include <iostream>
using namespace std;

class FirstClass
{
    public:
        FirstClass(int _vx) : vx(_vx) {}
        int x () {return vx;}
    private:
        int vx;
};

class SecondClass
{
    public:
        FirstClass Member1(666);
};

int main ()
{
    SecondClass Object2;
    cout << Object2.Member1.x();
    return 0;
}

我什至无法编译它。所以,我的问题是:如何在 SecondClass 的声明中将参数传递给 FirstClass 的构造函数?

提前致谢。

【问题讨论】:

  • 我在相关主题中找到了答案;抱歉重复...

标签: c++ class constructor arguments


【解决方案1】:

你必须在 SecondClass 的构造函数中将初始化值传递给 FirstClass,像这样:

class SecondClass:
   {
   public:
      SecondClass() : Member1(666) {}
      Firstclass Member1;
   };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-10-11
    相关资源
    最近更新 更多