C语言“翻译”C++结构体中的成员函数


C++结构体中的成员函数其实是一种“障眼法”,用C“翻译”一遍成员函数的实现,对理解成员函数有很大帮助。以年月日的结构体为例


/********************        C++中结构的成员函数C语言的实现        **************************/

#include <iostream>                             	// #include <stdio.h>
using namespace std;
struct Date{//C++中结构体中可以含有成员函数。        	// struct Date{
    int Year;                                   	//     int Year;
    int Month;                                  	//     int Month;
    int Day;                                    	//     int Day;
    void Input(){                               	// };
        cout<<"请输入年月日:";                   	// void Input(struct *This){
        cin>>Year>>Month>>Day;                 		//     printf("请输入年月日:");
    }                                           	//     scanf("%d %d %d",&This->Year,&This->Month,&This->Day);
    void Print(){                               	// }
        cout<<Year<<"年"<<Month<<"月"<<Day<<endl;	//  void Print(struct *This){
    }                                           	//     printf("%d年%d月%d日\n",This->Year,This->Month,This->Day);
};                                              	// }

int main(int argc, const char * argv[]) {       	// int main(int argc, const char * argv[]) {
    // insert code here...
    Date d1, d2;//C++中定义结构变量不用加struct    	//    struct Date d1, d2;
    d1.Input();                                 	//    Input(&d1);
    d2.Input();                                 	//    Print(&d2);
    d1.Print();                                 	//    Input(&d1);
    d2.Print();                                 	//    Print(&d2);
    
    return 0;                                   	//    return 0;
}                                               	// }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值