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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Apr 30, 2025 pm 07:24 PM

The built-in quantization tools on the exchange include: 1. Binance: Provides Binance Futures quantitative module, low handling fees, and supports AI-assisted transactions. 2. OKX (Ouyi): Supports multi-account management and intelligent order routing, and provides institutional-level risk control. The independent quantitative strategy platforms include: 3. 3Commas: drag-and-drop strategy generator, suitable for multi-platform hedging arbitrage. 4. Quadency: Professional-level algorithm strategy library, supporting customized risk thresholds. 5. Pionex: Built-in 16 preset strategy, low transaction fee. Vertical domain tools include: 6. Cryptohopper: cloud-based quantitative platform, supporting 150 technical indicators. 7. Bitsgap:

How to download, install and register the Hong Kong Digital Currency Exchange app 2025 How to download, install and register the Hong Kong Digital Currency Exchange app 2025 Apr 30, 2025 pm 07:18 PM

The download, installation and registration process of the Hong Kong Digital Currency Exchange app is very simple. Users can quickly obtain and use this app through the official app download link provided in this article. This article will introduce in detail how to download, install and register the Hong Kong Digital Currency Exchange app to ensure that every user can complete the operation smoothly.

How does deepseek official website achieve the effect of penetrating mouse scroll event? How does deepseek official website achieve the effect of penetrating mouse scroll event? Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

Easeprotocol.com directly implements ISO 20022 message standard as a blockchain smart contract Easeprotocol.com directly implements ISO 20022 message standard as a blockchain smart contract Apr 30, 2025 pm 05:06 PM

This groundbreaking development will enable financial institutions to leverage the globally recognized ISO20022 standard to automate banking processes across different blockchain ecosystems. The Ease protocol is an enterprise-level blockchain platform designed to promote widespread adoption through easy-to-use methods. It announced today that it has successfully integrated the ISO20022 messaging standard and directly incorporated it into blockchain smart contracts. This development will enable financial institutions to easily automate banking processes in different blockchain ecosystems using the globally recognized ISO20022 standard, which is replacing the Swift messaging system. These features will be tried soon on "EaseTestnet". EaseProtocolArchitectDou

Is there a future for digital currency apps? Apple mobile digital currency trading platform app download TOP10 Is there a future for digital currency apps? Apple mobile digital currency trading platform app download TOP10 Apr 30, 2025 pm 07:00 PM

The prospects of digital currency apps are broad, which are specifically reflected in: 1. Technology innovation-driven function upgrades, improving user experience through the integration of DeFi and NFT and AI and big data applications; 2. Regulatory compliance trends, global framework improvements and stricter requirements for AML and KYC; 3. Function diversification and service expansion, integrating lending, financial management and other services and optimizing user experience; 4. User base and global expansion, and the user scale is expected to exceed 1 billion in 2025.

uniswap on-chain withdrawal uniswap on-chain withdrawal Apr 30, 2025 pm 07:03 PM

Uniswap users can withdraw tokens from liquidity pools to their wallets to ensure asset security and liquidity. The process requires gas fees and is affected by network congestion.

Top 10 digital currency trading platforms: Top 10 safe and reliable digital currency exchanges Top 10 digital currency trading platforms: Top 10 safe and reliable digital currency exchanges Apr 30, 2025 pm 04:30 PM

The top 10 digital virtual currency trading platforms are: 1. Binance, 2. OKX, 3. Coinbase, 4. Kraken, 5. Huobi Global, 6. Bitfinex, 7. KuCoin, 8. Gemini, 9. Bitstamp, 10. Bittrex. These platforms all provide high security and a variety of trading options, suitable for different user needs.

What are the three giants in the currency circle? Top 10 Recommended Virtual Currency Main Exchange APPs What are the three giants in the currency circle? Top 10 Recommended Virtual Currency Main Exchange APPs Apr 30, 2025 pm 06:27 PM

In the currency circle, the so-called Big Three usually refers to the three most influential and widely used cryptocurrencies. These cryptocurrencies have a significant role in the market and have performed well in terms of transaction volume and market capitalization. At the same time, the mainstream virtual currency exchange APP is also an important tool for investors and traders to conduct cryptocurrency trading. This article will introduce in detail the three giants in the currency circle and the top ten mainstream virtual currency exchange APPs recommended.

See all articles