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;
} // }