[英]Derived class instance in the base class
This is the code I'm trying to understand. 这是我想要理解的代码。 It has no specific use.
没有特定用途。 I'm just trying to understand what happens.
我只是想了解会发生什么。
#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;
}
Using VS2013 I get the error "derivedClass: class has no constructors", which I don't think is the right error. 使用VS2013,我收到错误“ derivedClass:类没有构造函数”,我认为这不是正确的错误。
I was first using a derivedClass instance, not a pointer. 我首先使用的是derivedClass实例,而不是指针。 And that was giving me a weird error about a semicolon.
这给了我一个关于分号的怪异错误。 Then I saw this post where the accepted answer was to have a pointer, instead of an instance.
然后,我看到了这篇文章 ,其中可接受的答案是使用指针而不是实例。
These are the questions I have: 这些是我的问题:
Cheers. 干杯。
You're making use of the definition of derivedClass
before it's defined, by calling new derivedClass
in the baseClass
constructor. 通过在
baseClass
构造函数中调用new derivedClass
,您可以在定义derivedClass
之前使用它。 What you need to do is move the constructor definition outside baseClass
and after derivedClass
, like so: 您需要做的是将构造函数定义
baseClass
之外,然后derivedClass
到baseClass
之后,就像这样:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.