这是Instance-level encapsulation with C++的后续文章。
我已经定义了一个类并从该类创建了两个对象。
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
class timeclass {
private:
string date;
time_t gmrawtime, rawtime;
struct tm * timeinfo;
char file_date[9];
void tm_init(int);
public:
timeclass(int);
void print_date();
};
void timeclass::tm_init(int y) {
timeinfo = gmtime(&rawtime);
timeinfo->tm_year = y - 1900; // timeinfo->tm_year holds number of years since 1900
timeinfo->tm_mon = 0;
timeinfo->tm_mday = 1;
timeinfo->tm_hour = 0;
timeinfo->tm_min= 0;
timeinfo->tm_sec= 0;
}
timeclass::timeclass(int y) {
timeclass::tm_init(y);
gmrawtime = mktime(timeinfo) - timezone;
}
void timeclass::print_date() {
strftime(file_date,9,"%Y%m%d",timeinfo);
date = string(file_date);
cout<<date<<endl;
}
/* -----------------------------------------------------------------------*/
int main()
{
timeclass time1(1991);
timeclass time2(1992);
time1.print_date(); // Prints 19920101, despite being initialized with 1991
time2.print_date(); // Prints 19920101, as expected
return 0;
}
这个例子是从我的主程序中切分出来的日期计数器的一部分,但它说明了我的观点。我想为类的每个实例(time1 和 time2)运行一个日期计数器,但看起来一旦我构造了 time2 对象,我认为封装在 time1 中的“timeinfo”变量就会被 time2 构造函数覆盖。
我知道 C++ 仅支持类级封装,并且想知道我的问题是否是因为同一类的成员可以访问彼此的私有成员。有没有办法解决这个问题,所以我可以实现我想做的事情?谢谢你,泰勒