class和struct的区别
在C++中二者的区别只是默认访问权限不同:class成员的默认访问权限是private,而struct是public;在C中,除上述区别外,struct内没有成员函数(成员方法)
慢慢来,会好的
#include<iostream>
using namespace std;
class MyDate
{public://如果不写public就会默认为private
void InitMyDate()
{
cout << "year " << "month " << "day " << endl;
cin >> year;
cin >> month;
cin >> day;
}
bool IsLeapYear()
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
}
void PrintMyDate()
{
cout << year <<"年"<< month<<"月" << day <<"日"<< endl;
}
int GetYear()//为了获得year,可以使用此公开成员函数
{
return year;
}
private:
int year;
int month;
int day;
};
int main()
{
MyDate date1;
date1.InitMyDate();
date1.PrintMyDate();
if (date1.IsLeapYear() == 1)
cout <<date1.GetYear()<< "是闰年" << endl;//date1.year是不对的,year是私有成员,此处已经是类外
else
cout << date1.GetYear() <<"不是闰年" << endl;
system("pause");
return 0;
}