国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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>

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>

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

 <code class="c">typedef struct { VehicleType type; int (*price)(void*); // 函數(shù)指針,指向價(jià)格計(jì)算函數(shù)} Vehicle;</code>

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>

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>

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; // 強(qiáng)制類型轉(zhuǎn)換Vehicle motorcycle_v = {VEHICLE_MOTORCYCLE, motorcycle_price}; ((Motorcycle*)&motorcycle_v)->cc = 1000; // 強(qiáng)制類型轉(zhuǎn)換print_vehicle_price(&car_v); print_vehicle_price(&motorcycle_v); free((Car*)&car_v); free((Motorcycle*)&motorcycle_v); return 0; }</code>

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Leading the top 20 token rankings in the 2025 crypto market (Latest update) Leading the top 20 token rankings in the 2025 crypto market (Latest update) Jul 10, 2025 pm 08:48 PM

The top 20 most promising crypto assets in 2025 include BTC, ETH, SOL, etc., mainly covering multiple tracks such as public chains, Layer 2, AI, DeFi and gaming. 1.BTC continues to lead the market with its digital yellow metallicity and popularization of ETFs; 2.ETH consolidates the ecosystem due to its position and upgrade of smart contract platforms; 3.SOL stands out with high-performance public chains and developer communities; 4.LINK is the leader in oracle connecting real data; 5.RNDR builds decentralized GPU network service AI needs; 6.IMX focuses on Web3 games to provide a zero-gas-free environment; 7.ARB leads with mature Layer 2 technology and huge DeFi ecosystem; 8.MATIC has become the value layer of Ethereum through multi-chain evolution

Comparison of the differences and advantages and disadvantages of USDC, DAI, and TUSD (recently updated) Comparison of the differences and advantages and disadvantages of USDC, DAI, and TUSD (recently updated) Jul 10, 2025 pm 09:09 PM

The core difference between USDC, DAI and TUSD lies in the issuance mechanism, collateral assets and risk characteristics. 1. USDC is a centralized stablecoin issued by Circle and is collateralized by cash and short-term treasury bonds. Its advantages are compliance and transparent, strong liquidity, and high stability, but there is a risk of centralized review and single point failure; 2. DAI is a decentralized stablecoin, generated through the MakerDAO protocol, and the collateral is a crypto asset. It has the advantages of anti-censorship, transparency on chain, and permission-free, but it also faces systemic risks, dependence on centralized assets and complexity issues; 3. TUSD is a centralized stablecoin, emphasizing real-time on-chain reserve proof, providing higher frequency transparency verification, but has a small market share and weak liquidity. The three are collateral types and decentralization

The TOP5 cryptocurrency platforms that are most suitable for Asian users (2025 latest rankings) The TOP5 cryptocurrency platforms that are most suitable for Asian users (2025 latest rankings) Jul 11, 2025 pm 09:42 PM

In the global wave of digital asset trading, it is crucial to choose a safe, efficient and trading platform that meets your own needs. Especially for users in Asia, facing many platforms, complex functions and changing regulatory environments, how to find the best cryptocurrency platform for you and find the best cryptocurrency platform for you has become a problem for many people. This article aims to provide you with an in-depth analysis of the TOP5 cryptocurrency platforms that are most suitable for Asian users in 2025, helping you move forward steadily in the world of digital assets.

Tutorial on one-click update of Ouyi new version v6.127_Quick update operation of Ouyi new version v6.127 Android Tutorial on one-click update of Ouyi new version v6.127_Quick update operation of Ouyi new version v6.127 Android Jul 11, 2025 pm 10:09 PM

The latest version of Ouyi is v6.1271, and the update tutorial is: 1. Uninstall the old version or unofficial APK; 2. Click the official download address provided by the article to download the latest APK; 3. Enable the mobile phone installation permission; 4. Install and log in to the verification function. It is recommended to use v6.127.0 or higher. If the current version is lower than v6.124 or comes from a third-party platform, you should immediately switch to the official channel to ensure transaction security and stable functions.

The flow of funds on the chain is exposed: What new tokens are being bet on by Clever Money? The flow of funds on the chain is exposed: What new tokens are being bet on by Clever Money? Jul 16, 2025 am 10:15 AM

Ordinary investors can discover potential tokens by tracking "smart money", which are high-profit addresses, and paying attention to their trends can provide leading indicators. 1. Use tools such as Nansen and Arkham Intelligence to analyze the data on the chain to view the buying and holdings of smart money; 2. Use Dune Analytics to obtain community-created dashboards to monitor the flow of funds; 3. Follow platforms such as Lookonchain to obtain real-time intelligence. Recently, Cangming Money is planning to re-polize LRT track, DePIN project, modular ecosystem and RWA protocol. For example, a certain LRT protocol has obtained a large amount of early deposits, a certain DePIN project has been accumulated continuously, a certain game public chain has been supported by the industry treasury, and a certain RWA protocol has attracted institutions to enter.

AI, Customer Acquisition, and Costs: O'Leary's Perspective on the Future of Business AI, Customer Acquisition, and Costs: O'Leary's Perspective on the Future of Business Jul 11, 2025 am 10:54 AM

Kevin O'Leary highlights AI's transformative impact on reducing customer acquisition costs, reshaping investment strategies, and the US-China tech rivalry.

Latest cryptocurrency market forecast (2025-2030) Latest cryptocurrency market forecast (2025-2030) Jul 11, 2025 pm 08:51 PM

The price potential of major crypto assets from 2025 to 2030 is driven by technological development, market cycles and macroeconomics. 1. Bitcoin (BTC) is expected to break through the historical high in 2025 due to the halving event and the launch of ETFs, and may reach a new order of magnitude in 2030; 2. Ethereum (ETH) benefits from network upgrades and ecological expansion, and its long-term value is bullish; 3. Projects such as Solana, BNB, and Chainlink rely on ecological development and technological stability, and the overall market will mature but be accompanied by high risks.

Ouyi okex Android genuine 2025 latest official version v6.128.0 Ouyi okex Android genuine 2025 latest official version v6.128.0 Jul 10, 2025 pm 09:24 PM

Ouyi okex is a professional digital asset trading and management tool, providing users with safe, stable and reliable trading services. It supports the transaction of a variety of mainstream digital assets and provides a wealth of financial tools and products to help users easily manage and configure their own digital assets.

See all articles