c++ - 如何将对象作为另一个类构造函数的参数传递?

标签 c++ oop constructor

我有 2 个类,一个类从抽象类继承它的参数:

class Child : public Base {
public:
    Child(string s, int i, ) : Base(s, i){};
    ... // methods
};

另一个有两个重载的构造函数,一个使用普通参数,另一个使用相同的参数,但是来自第一个类的已经存在的对象:

头文件:

class Other {
private:
    string s;
    int i; 
    Child o;
public:
    Other(string str, int num);
    Other(Child ob);
};

cpp文件:

Other :: Other(string str, int num) : s(str), i(num) {/* this is where the error happens*/};
Other :: Other(Child ob) : o(ob) {
};

但是当我尝试编译时,我在标记位置“C2512 'Other': no appropriate default constructor available”出现错误

可能是什么问题?我真的需要将该对象传递给构造函数

最佳答案

这里:

Other :: Other(string str, int num) : s(str), i(num)

您需要构造子对象:

Other :: Other(string str, int num) : s(str), i(num), o(str, num ) {}

关于c++ - 如何将对象作为另一个类构造函数的参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090631/

相关文章:

php - 在 oop 中设置全局变量的最佳方法?

java - 在 java 中,使用 "new"初始化数组有什么好处?

c++ - 仅专门化嵌套模板

c++ - Cin 不是 "working"吗?

c++ - 用于实时应用程序的 FEM 库

c# - c#构造函数的问题

c++ - 如何使用2d数组作为参数创建C++构造函数

c++ - 如何在 Linux 和 Windows 上获取时间戳字符串

c++ - 在循环构造函数调用中创建的对象的拷贝

c++ - OOP 游戏菜单系统开发概念化