C++给结构增加了一种新成员类型-------在C++中,结构可以包含函数,这意味着通过给结构增加函数,就使结构可以包含所绑定的算法,而这些算法还可作于其他结构成员。让算法与算法处理的数据密切关联,这种关联就是C++支持封装的方式。
如下提供一段为结构增加函数的代码:
#include "stdafx.h"
#include <iostream>
struct Date{
int month,day,year;
void display();
};
void Date::display(){
static char* mon[]={
"January","February","March","April","May"
,"June","July","August","Setember","October","November","December"
};
std::cout<<mon[month-1]<<" "<<day<<","<<year<<"\n";
}
int main(int argc, char* argv[])
{
Date birthday={4,6,1961};
std::cout<<"terry is date birth is ";
birthday.display();
return 0;
}
#include <iostream>
struct Date{
int month,day,year;
void display();
};
void Date::display(){
static char* mon[]={
"January","February","March","April","May"
,"June","July","August","Setember","October","November","December"
};
std::cout<<mon[month-1]<<" "<<day<<","<<year<<"\n";
}
int main(int argc, char* argv[])
{
Date birthday={4,6,1961};
std::cout<<"terry is date birth is ";
birthday.display();
return 0;
}
以上程序代码,把类声明外的display函数声明记做Date::display。这种写法告诉C++编绎器,存在支持Date 结构实例的显示成员函数。事实上,只有己声明的Date 的结构成员才能调用这个显示函数。
程序中的main 函数声明一个名为birthday的Date 实例,并让其初始化。然后,main 函数调用Date::display函数,把它看成birthday变量的结构成员,写法如下:
birthday.display();
Date::display 函数可以直接引用结构中其他相关成员,而不必在成员名前加上结构的实例名,因为函数本身就是结构成员。Date::display 函数还声明了一个指向字符串数组的指针数组,它用字符串初始化。
TIP:实现结构函数体的函数名必须与结构类型一致。
运行效果如下:
上面的代码我们还可以在main 函数里面声明同一结构的多个实例,在为某个特定结构对象调用函数时,成员函数把自己与对象的数据关联起来。代码如下:
#include "stdafx.h"
#include <iostream>
struct Date{
int month,day,year;
void display();
};
void Date::display(){
static char* mon[]={
"January","February","March","April","May"
,"June","July","August","Setember","October","November","December"
};
std::cout<<mon[month-1]<<" "<<day<<","<<year<<"\n";
}
int main(int argc, char* argv[])
{
Date birthday={4,6,1961};
std::cout<<"terry is date birth is ";
birthday.display();
Date sharons_birthday={10,12,1988};
std::cout<<"Share's date of birthday";
sharons_birthday.display();
Date wndys_birthday={4,28,1999};
std::cout<<"wndy's date of birth is ";
wndys_birthday.display();
return 0;
}
#include <iostream>
struct Date{
int month,day,year;
void display();
};
void Date::display(){
static char* mon[]={
"January","February","March","April","May"
,"June","July","August","Setember","October","November","December"
};
std::cout<<mon[month-1]<<" "<<day<<","<<year<<"\n";
}
int main(int argc, char* argv[])
{
Date birthday={4,6,1961};
std::cout<<"terry is date birth is ";
birthday.display();
Date sharons_birthday={10,12,1988};
std::cout<<"Share's date of birthday";
sharons_birthday.display();
Date wndys_birthday={4,28,1999};
std::cout<<"wndy's date of birth is ";
wndys_birthday.display();
return 0;
}
运行效果如下:
新手初学,还有很多不懂,请各位大侠赐教。
本文转自 terry_龙 51CTO博客,原文链接:http://blog.51cto.com/terryblog/405797,如需转载请自行联系原作者