[英]abstract class and virtual functions
Would this class be considered an abstract class because it has one virtual function?这个类是否会被认为是一个抽象类,因为它有一个虚函数? I was still able to create an Animal object and call getFoodCost();
我仍然能够创建一个 Animal 对象并调用 getFoodCost();
I thought abstract classes cannot be instantiated.我认为抽象类不能被实例化。 Does this mean objects can have virtual functions and not be considered abstract class?
这是否意味着对象可以具有虚函数而不被视为抽象类?
class Animal
{
public:
Animal();
int getBabies();
double getFoodCost();
virtual double getPayOff();
int getQty();
void incAge();
void setAge(int);
protected:
int counter=0;
int age;
int cost;
};
Would this class be considered an abstract class because it has one virtual function?
这个类是否会被认为是一个抽象类,因为它有一个虚函数? I was still able to create an Animal object and call getFoodCost();
我仍然能够创建一个 Animal 对象并调用 getFoodCost();
No. In C++, "Abstract Class" usually refers to a class with a pure virtual function :不。在 C++ 中,“抽象类”通常是指具有纯虚函数的类:
class Abstract {
public:
virtual void PureVirtual() = 0; // no implementation
};
class NotAbstract {
virtual void NotPureVirutal() {
// Some implementation
}
};
I thought abstract classes cannot be instantiated.
我认为抽象类不能被实例化。
Yes, that is correct.对,那是正确的。 This is because abstract classes have functions with no required implementation.
这是因为抽象类具有不需要实现的函数。 It has no way to instantiate an instance directly.
它没有办法直接实例化一个实例。 It uses inheritance and pointers/references to refer to an abstract class.
它使用继承和指针/引用来引用抽象类。
Does this mean objects can have virtual functions and not be considered abstract class?
这是否意味着对象可以具有虚函数而不被视为抽象类?
Yes.是的。 Again, abstract classes are classes that have pure virtual functions.
同样,抽象类是具有纯虚函数的类。 This is different from a regular virtual function.
这与常规的虚函数不同。 As discussed above, pure virtual functions have no required implementation.
如上所述,纯虚函数不需要实现。 Regular virtual functions, on the other hand, are required to have an implementation associated with them, so they can be instantiated.
另一方面,常规虚函数需要有一个与它们相关联的实现,因此它们可以被实例化。
An abstract function is a virtual
member function for which you do = 0
, as in抽象函数是一个
virtual
成员函数,您对其执行= 0
,如
virtual double getPayOff() = 0;
A class with at least one abstract function, including inherited ones, is an abstract class.具有至少一个抽象函数(包括继承的函数)的类是抽象类。 A class with only pure virtual functions is a so-called pure abstract class (also known as an interface class).
只有纯虚函数的类是所谓的纯抽象类(也称为接口类)。
Since your getPayOff
function isn't pure virtual, your class isn't abstract either.由于您的
getPayOff
函数不是纯虚拟的,因此您的类也不是抽象的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.