gpt4 book ai didi

c++ - 从嵌套抽象父类调用构造函数的问题

转载 作者:行者123 更新时间:2023-12-02 09:49:33 30 4
gpt4 key购买 nike

我有以下代码片段,希望从父类First::Inner调用构造函数。

class First {
public:
class Inner {
public:
Inner(int x) {}
virtual ~Inner() = default;
};
virtual Inner* begin() = 0;
};

class Second: public First {
public:
class Inner: public First::Inner {
};
Inner* begin() {
return new Inner(1);
}
};

int main()
{
Second s;

return 0;
}

相反,我在编译器中遇到了编译错误:
main.cpp: In member function ‘virtual Second::Inner* Second::begin()’:
main.cpp:16:31: error: no matching function for call to ‘Second::Inner::Inner(int)’

如果将整个构造函数 Inner(int x) {}从基类 First::Inner移到派生的 Second::Inner,它将起作用。但是我想将构造函数保留在基类中。

代码有什么问题,我该如何解决该错误?

最佳答案

问题在于类Second::Inner没有使用int的构造函数,因此new Inner(1);将会失败。

你可以像这样inherit constructor

class Inner: public First::Inner {
using First::Inner::Inner;
};

LIVE

If the using-declaration refers to a constructor of a direct base of the class being defined (e.g. using Base::Base;), all constructors of that base (ignoring member access) are made visible to overload resolution when initializing the derived class.

If overload resolution selects one of the inherited constructors when initializing an object of such derived class, then the Base subobject from which the constructor was inherited is initialized using the inherited constructor, and all other bases and members of Derived are initialized as if by the defaulted default constructor (default member initializers are used if provided, otherwise default initialization takes place). The entire initialization is treated as a single function call: initialization of the parameters of the inherited constructor is sequenced-before initialization of any base or member of the derived object.

关于c++ - 从嵌套抽象父类调用构造函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61335079/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com