Home Backend Development C++ Object-oriented in C? Implementing interfaces from scratch

Object-oriented in C? Implementing interfaces from scratch

Apr 03, 2025 pm 08:21 PM
c language ai switch typedef 2025

Object-oriented in C? Implementing interfaces from scratch

This article discusses how to simulate the concept of interfaces in object-oriented programming in C language. We will take the calculation of vehicle prices as an example, implement them in Java and C languages ​​respectively, compare the differences between the two languages, and show how to implement the basic functions of the interface in C.

Java implementation:

In Java, interface is defined using the interface keyword, and classes implement interfaces through implements keyword. The sample code is as follows:

 <code class="java">interface Vehicle { int price(); } class Car implements Vehicle { private final int speed; public Car(int speed) { this.speed = speed; } @Override public int price() { return speed * 60; } } class Motorcycle implements Vehicle { private final int cc; public Motorcycle(int cc) { this.cc = cc; } @Override public int price() { return cc * 10; } } public class Main { public static void printVehiclePrice(Vehicle vehicle) { System.out.println("$" vehicle.price() ".00"); } public static void main(String[] args) { Car car = new Car(120); Motorcycle motorcycle = new Motorcycle(1000); printVehiclePrice(car); printVehiclePrice(motorcycle); } }</code>
Copy after login

C language implementation:

There is no direct interface mechanism in C language. We can simulate the behavior of an interface by enumerating types, structures, and function pointers.

First define the enumeration type to represent the vehicle type:

 <code class="c">typedef enum { VEHICLE_CAR, VEHICLE_MOTORCYCLE } VehicleType;</code>
Copy after login

Then define the vehicle structure, including type information and function pointers:

 <code class="c">typedef struct { VehicleType type; int (*price)(void*); // 函数指针,指向价格计算函数} Vehicle;</code>
Copy after login

Next, realize the structure of automobile and motorcycle:

 <code class="c">typedef struct { VehicleType type; int speed; } Car; typedef struct { VehicleType type; int cc; } Motorcycle;</code>
Copy after login

The corresponding initialization and price calculation functions:

 <code class="c">Car* car_init(int speed) { Car* car = malloc(sizeof(Car)); car->type = VEHICLE_CAR; car->speed = speed; return car; } int car_price(void* car) { return ((Car*)car)->speed * 60; } Motorcycle* motorcycle_init(int cc) { Motorcycle* motorcycle = malloc(sizeof(Motorcycle)); motorcycle->type = VEHICLE_MOTORCYCLE; motorcycle->cc = cc; return motorcycle; } int motorcycle_price(void* motorcycle) { return ((Motorcycle*)motorcycle)->cc * 10; }</code>
Copy after login

Finally, implement the vehicle_price function and call different price calculation functions according to the vehicle type:

 <code class="c">int vehicle_price(Vehicle* vehicle) { switch (vehicle->type) { case VEHICLE_CAR: return car_price((Car*)vehicle); case VEHICLE_MOTORCYCLE: return motorcycle_price((Motorcycle*)vehicle); default: return 0; } } void print_vehicle_price(Vehicle* vehicle) { printf("$%d.00\n", vehicle_price(vehicle)); } int main() { Vehicle car_v = {VEHICLE_CAR, car_price}; ((Car*)&car_v)->speed = 120; // 强制类型转换Vehicle motorcycle_v = {VEHICLE_MOTORCYCLE, motorcycle_price}; ((Motorcycle*)&motorcycle_v)->cc = 1000; // 强制类型转换print_vehicle_price(&car_v); print_vehicle_price(&motorcycle_v); free((Car*)&car_v); free((Motorcycle*)&motorcycle_v); return 0; }</code>
Copy after login

This C language implementation simulates the behavior of interfaces, but requires manual management of memory and type conversion, which is more complex than Java's interface mechanism. This approach improves the maintainability and readability of the code when dealing with complex data structures, such as abstract syntax trees (AST).

The above is the detailed content of Object-oriented in C? Implementing interfaces from scratch. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the syntax for adding columns in SQL What is the syntax for adding columns in SQL Apr 09, 2025 pm 02:51 PM

The syntax for adding columns in SQL is ALTER TABLE table_name ADD column_name data_type [NOT NULL] [DEFAULT default_value]; where table_name is the table name, column_name is the new column name, data_type is the data type, NOT NULL specifies whether null values ​​are allowed, and DEFAULT default_value specifies the default value.

SQL Clear Table: Performance Optimization Tips SQL Clear Table: Performance Optimization Tips Apr 09, 2025 pm 02:54 PM

Tips to improve SQL table clearing performance: Use TRUNCATE TABLE instead of DELETE, free up space and reset the identity column. Disable foreign key constraints to prevent cascading deletion. Use transaction encapsulation operations to ensure data consistency. Batch delete big data and limit the number of rows through LIMIT. Rebuild the index after clearing to improve query efficiency.

How to set default values ​​when adding columns in SQL How to set default values ​​when adding columns in SQL Apr 09, 2025 pm 02:45 PM

Set the default value for newly added columns, use the ALTER TABLE statement: Specify adding columns and set the default value: ALTER TABLE table_name ADD column_name data_type DEFAULT default_value; use the CONSTRAINT clause to specify the default value: ALTER TABLE table_name ADD COLUMN column_name data_type CONSTRAINT default_constraint DEFAULT default_value;

Use DELETE statement to clear SQL tables Use DELETE statement to clear SQL tables Apr 09, 2025 pm 03:00 PM

Yes, the DELETE statement can be used to clear a SQL table, the steps are as follows: Use the DELETE statement: DELETE FROM table_name; Replace table_name with the name of the table to be cleared.

How to deal with Redis memory fragmentation? How to deal with Redis memory fragmentation? Apr 10, 2025 pm 02:24 PM

Redis memory fragmentation refers to the existence of small free areas in the allocated memory that cannot be reassigned. Coping strategies include: Restart Redis: completely clear the memory, but interrupt service. Optimize data structures: Use a structure that is more suitable for Redis to reduce the number of memory allocations and releases. Adjust configuration parameters: Use the policy to eliminate the least recently used key-value pairs. Use persistence mechanism: Back up data regularly and restart Redis to clean up fragments. Monitor memory usage: Discover problems in a timely manner and take measures.

phpmyadmin creates data table phpmyadmin creates data table Apr 10, 2025 pm 11:00 PM

To create a data table using phpMyAdmin, the following steps are essential: Connect to the database and click the New tab. Name the table and select the storage engine (InnoDB recommended). Add column details by clicking the Add Column button, including column name, data type, whether to allow null values, and other properties. Select one or more columns as primary keys. Click the Save button to create tables and columns.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to create an oracle database How to create an oracle database How to create an oracle database How to create an oracle database Apr 11, 2025 pm 02:33 PM

Creating an Oracle database is not easy, you need to understand the underlying mechanism. 1. You need to understand the concepts of database and Oracle DBMS; 2. Master the core concepts such as SID, CDB (container database), PDB (pluggable database); 3. Use SQL*Plus to create CDB, and then create PDB, you need to specify parameters such as size, number of data files, and paths; 4. Advanced applications need to adjust the character set, memory and other parameters, and perform performance tuning; 5. Pay attention to disk space, permissions and parameter settings, and continuously monitor and optimize database performance. Only by mastering it skillfully requires continuous practice can you truly understand the creation and management of Oracle databases.

See all articles