#include<iostream>
using namespace std;
class Box{
public:
Box(int,int);
int volume();
static int height;
int width;
int length;
};
Box::Box(int w,int l)
{
width=w;
length=l;
}
int Box::volume()
{
return (height*width*length);
}
int Box::height=10;
int main()
{
Box box1(10,15);
Box box2(15,20);
cout<<box1.height<<endl;
cout<<box2.height<<endl;
cout<<Box::height<<endl;
cout<<box1.volume()<<endl;
return 0;
}友元
#include<iostream>
using namespace std;
class Time{
public:
Time(int,int,int);
friend void display(Time &);
private:
int hour;
int minute;
int sec;
};
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
void display(Time &t)
{
cout<<t.hour <<":"<<t.minute <<":"<<t.sec <<endl;
}
int main()
{
Time t1(12,23,34);
display(t1);
return 0;
}*/
#include<iostream>
using namespace std;
class Date;
class Time{
public:
Time(int,int,int);
void display(Date &);
private:
int hour;
int minute;
int sec;
};
class Date{
public:
Date(int,int,int);
friend void Time:: display(Date &);
private:
int year;
int month;
int day;
};
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
void Time::display(Date &d)
{
cout<<d.year<<"/"<<d.month <<"/"<<d.day <<endl;
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
int main()
{
Time t1(12,23,34);
Date d1(2004,12,23);
t1.display(d1);
return 0;
}
本文深入探讨了C++编程中的静态成员和友元的概念。静态成员允许在类的所有实例间共享数据,而友元则提供了打破类封装的方式,使得非成员函数或类可以访问私有和受保护的成员。通过理解这两个关键特性,开发者能更好地掌握C++类的设计和实现。

803

被折叠的 条评论
为什么被折叠?



