没有默认ctor的C ++私有变量-无法编译? [英] C++ private variable with no default ctor - not compiling?

查看:74
本文介绍了没有默认ctor的C ++私有变量-无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有默认构造函数的obj1类,也没有一个默认构造函数的obj2类,并且具有obj1元素作为私有变量:

I have a class obj1 that has no default constructor, and class obj2 that also doesn't have a default constructor, and has as private variable an element of obj1:

我想要类似以下代码的内容-但实际上这不能编译,告诉我obj1没有默认构造函数。

I would like something like the following code - but actually this doesn't compile, telling me that obj1 has no default constructor.

class obj1{
    obj1(some parameters){};
}

class obj2{
    obj1 _myObj1;
    obj2(some parameters){
        _myObj1 = obj1(some parameters)
    }
} 

有什么想法吗?

推荐答案

构造 obj1 公开并使用 obj2 中的初始化列表。

Make the constructor of obj1 public and use initialization list in obj2.

class obj1{
public:
    obj1(some parameters){};
};

class obj2{
    obj1 _myObj1;
    obj2(some parameters) : _myObj1(some parameters) {
    }
};

这篇关于没有默认ctor的C ++私有变量-无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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