I have the following code
class interfaceBase // abstract class
{
public:
virtual void vf1() = 0;
};
class tempBase : public interfaceBase // manages a resource
{
tempBase(int a) { var = new int[a]; }
~tempBase(){ free(var); }
private:
int* var;
};
class derived : public tempBase // class I intend to instantiate.
{
public:
derived(int rhs){ tempBase(var); } // ERROR - Pasted below
void vf1() override final {}
};
int main()
{
int a = 5;
derived d(a);
}
I have a resource that needs to be managed, I created a seperate class called tempBase
whose job is to manage that resource. However, this leaves me with a problem - I cannot construct objects of type derived
, because there seems no means to call the constructor to tempBase
I get the error saying
error C2512: 'tempBase' : no appropriate default constructor available
error C2259: 'tempBase' : cannot instantiate abstract class
How can I change my code such that I might still have all the resource management handled by tempBase
, and have derived
instantiable also.
You ave to put this in the initializer list:
derived(int rhs) : tempBase(var) { } // No erroranymore - see below
Some additional explanation about the errors in your original code:
tempBase
, the compiler tried to generate a default constructor, so that all member variables are constructed before executing the constructor body. tempBase(var)
in the body would create an additional temporary anonymous object of class tempBase
, but such direct instantiation of a pure virtual class is not allowed 在构造派生对象的基础部分时,您需要使用
derived(vars) : base(vars) { constructor code here }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.