这是我想要了解的代码。它没有具体用途。我只是想了解会发生什么。
#include<iostream>
using namespace std;
class derivedClass;
class baseClass
{
public:
int objID;
derivedClass* dcObjPtr;
baseClass()
{
cout << "(1) Default constructor" << objID << endl;
}
baseClass(int ID)
{
objID = ID;
dcObjPtr = new derivedClass(1);
cout << "(2) Constructing base object with ID: " << objID << endl;
}
};
class derivedClass : public baseClass
{
public:
derivedClass()
{}
derivedClass(int ID) : baseClass(ID)
{
cout << "(4) Constructing derived object with ID: " << objID << endl;
}
};
int main(int argc, char** argv)
{
derivedClass dcObj(1);
return 0;
}
使用VS2013我得到错误“derivedClass:class has no constructors”,我认为这不是正确的错误。
我第一次使用的是derivedClass实例,而不是指针。这给了我一个关于分号的奇怪错误。然后我看到this post,其中接受的答案是指针,而不是实例。
这些是我的问题:
干杯。
答案 0 :(得分:1)
通过调用derivedClass
构造函数中的new derivedClass
,您可以在定义之前使用baseClass
的定义。您需要做的是将构造函数定义移到baseClass
之外和derivedClass
之后,如下所示:
#include<iostream>
using namespace std;
class derivedClass;
class baseClass
{
public:
int objID;
derivedClass* dcObjPtr;
baseClass()
{
cout << "(1) Default constructor" << objID << endl;
}
baseClass(int ID);
};
class derivedClass : public baseClass
{
public:
derivedClass()
{}
derivedClass(int ID) : baseClass(ID)
{
cout << "(4) Constructing derived object with ID: " << objID << endl;
}
};
baseClass::baseClass(int ID)
{
objID = ID;
dcObjPtr = new derivedClass(1);
cout << "(2) Constructing base object with ID: " << objID << endl;
}
int main(int argc, char** argv)
{
derivedClass dcObj(1);
return 0;
}