【发布时间】:2023-03-18 12:14:02
【问题描述】:
这是来自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++ 仅支持类级封装,我想知道我的问题是否是因为同一类的成员可以访问彼此的私有成员。有没有办法解决这个问题,所以我可以实现我想做的事情?谢谢, 泰勒
【问题讨论】:
-
避免使用
using namespace std;。有关说明,请参阅 here。 -
感谢@AxelOmega,我欢迎任何提示,因为我不是这方面的专家。您是否建议完全省略
using namespace std;,然后直接显式调用 std::cout(和 cout 以外的其他函数)? -
是的
std::cout是正常的。这在大多数 C++ 代码中也是正常的。如果您觉得不能再输入五个字符,您也可以使用using std::cout。但是std::会在一段时间后成为一种反射。
标签: c++ encapsulation