抽象类、抽象方法和虚函数是面向对象编程中重要的概念,在不同的编程语言(如 C++、C#、Java 等)中都有体现,下面以 C# 和 C++ 为例详细介绍。

抽象类

定义

抽象类是一种不能被实例化的类,它主要用于为其他类提供一个通用的基类,定义一组相关类的公共接口和行为。抽象类可以包含抽象方法和非抽象方法。

C# 示例

// 定义抽象类

abstract class Shape

{

// 抽象方法

public abstract double Area();

// 非抽象方法

public void Display()

{

Console.WriteLine("This is a shape.");

}

}

// 继承抽象类并实现抽象方法

class Circle : Shape

{

private double radius;

public Circle(double r)

{

radius = r;

}

public override double Area()

{

return Math.PI * radius * radius;

}

}

class Program

{

static void Main()

{

// Shape shape = new Shape(); // 错误,抽象类不能实例化

Circle circle = new Circle(5);

Console.WriteLine("Circle area: " + circle.Area());

circle.Display();

}

}

C++ 示例

#include

// 定义抽象类

class Shape {

public:

// 纯虚函数,使类成为抽象类

virtual double Area() = 0;

// 普通成员函数

void Display() {

std::cout << "This is a shape." << std::endl;

}

};

// 继承抽象类并实现纯虚函数

class Circle : public Shape {

private:

double radius;

public:

Circle(double r) : radius(r) {}

double Area() override {

return 3.14 * radius * radius;

}

};

int main() {

// Shape shape; // 错误,抽象类不能实例化

Circle circle(5);

std::cout << "Circle area: " << circle.Area() << std::endl;

circle.Display();

return 0;

}

抽象方法

定义

抽象方法是一种没有具体实现的方法,它只有方法的声明,没有方法体。抽象方法必须在抽象类中定义,并且要求任何继承该抽象类的非抽象子类都必须实现这些抽象方法。

C# 示例

在上述 C# 的 Shape 类中,Area 方法就是一个抽象方法,使用 abstract 关键字修饰。

public abstract double Area();

C++ 示例

在 C++ 中,抽象方法通过纯虚函数来实现,在函数声明后加上 = 0。

virtual double Area() = 0;

虚函数

定义

虚函数是在基类中使用 virtual 关键字声明的函数,它允许在派生类中重写该函数。通过基类的指针或引用调用虚函数时,会根据实际对象的类型来决定调用哪个版本的函数,从而实现多态性。

C# 示例

class Animal

{

public virtual void MakeSound()

{

Console.WriteLine("The animal makes a sound.");

}

}

class Dog : Animal

{

public override void MakeSound()

{

Console.WriteLine("The dog barks.");

}

}

class Program

{

static void Main()

{

Animal animal = new Dog();

animal.MakeSound(); // 输出 "The dog barks."

}

}

C++ 示例

#include

class Animal {

public:

virtual void MakeSound() {

std::cout << "The animal makes a sound." << std::endl;

}

};

class Dog : public Animal {

public:

void MakeSound() override {

std::cout << "The dog barks." << std::endl;

}

};

int main() {

Animal* animal = new Dog();

animal->MakeSound(); // 输出 "The dog barks."

delete animal;

return 0;

}

总结

抽象类:为派生类提供公共接口和行为的基类,不能实例化。 抽象类里也可以有非抽象方法

抽象方法:只有声明没有实现,强制子类实现,用于定义规范。抽象方法必须定义在抽象类中。

虚函数:允许在派生类中重写,通过基类指针或引用实现多态调用。