我的情况如下。设置头文件classdeclarations.h,在其中声明以下类:

class ClassA;
class ClassB;

class ClassA
    {
    public:
        ClassA(int x);
        ClassA(double y);

        int ReturnInteger(void) { return m_x; }
        double ReturnDouble(void) { return m_y; }
    private:
        int m_x;
        double m_y;
    }

class ClassB
    {
    public:
        ClassB(int x);

        int ReturnInteger(void) { return m_x; }
    private:
        int m_x;
        ClassA m_InstanceA_1;
    }


让我们创建一个名为*.cppclassdefns.cpp文件,在其中定义classdeclarations.h中声明的类的方法:

#include classdeclarations.h

ClassA::ClassA(int x) : m_x(x)
    {
    }

ClassA::ClassA(double y) : m_y(y)
    {
    }

ClassB::ClassB(int x) : m_x(x)
    {  //  this is the line where the build error occurs
    m_InstanceA_1 = ClassA(0);
    }


请注意,我已经在编译器说有错误的行中注释了:

error C2512: 'ClassA' : no appropriate default constructor available

上面的例子不是一个最小的不起作用的例子(它可能起作用),但是它捕获了我遇到错误的更复杂情况的要点。

This StackOverflow question regarding the same error was resolved by an answer that clarified where default arguments should be specified.在我的情况下,我不再有默认参数了(但是过去有)。我只是仔细检查以确保没有默认的构造函数参数。

This question regarding the same error was resolved by ensuring that the name of the constructors was the same as the name of the class.我已仔细检查以确保这不是我所遇到的问题。

This question regarding the same error is different from my case, because here the asker did not want to have a default constructor defined.

This question regarding the same error was resolved by ensuring that a default constructor method was declared in the body of the class declaration.因此,这不适用于我的情况,因为我已经在类声明中声明了构造函数。

This question regarding the same error was resolved by ensuring that the declaring header file was properly included.这不是我的问题。

This question regarding the same error is perhaps relevant, but I don't understand it well enough, and would appreciate clarification on where I might be assuming the existence of a default constructor?

最佳答案

ClassB::ClassB(int x) : m_x(x), m_InstanceA_1(0)
                                //^^^^^^^^^^^^, this constructs the ClassA instance
{
}


编辑


  获取C2512“没有默认构造函数”


如果仍然需要默认构造ClassA实例的功能,则需要添加默认构造函数。提供其他构造函数后,默认构造函数不再自动生成。

class ClassA
{
public:
    ClassA(); // Provides a default constructor declaration (you still need to implement it)
    ClassA(int x);
    ClassA(double y);

...
};

09-10 00:49
查看更多