這是從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++僅支持類級封裝,並且想知道我的問題是否因爲同一類的成員可以訪問彼此的私有成員。有沒有辦法解決這個問題,所以我可以實現我想要做的事情?謝謝你, 泰勒
避免做'使用命名空間std;'。請參閱[這裏](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c)的解釋。 – AxelOmega 2013-03-08 21:21:30
謝謝@AxelOmega,我歡迎任何提示,因爲我不是這方面的專家。你會建議省略'使用namespace std;',然後直接調用std :: cout(以及除cout之外的其他函數)嗎? – Taylor 2013-03-08 21:31:13
是'std :: cout'是正常的。在大多數C++代碼中也是正常的。如果你覺得你不能再輸入五個字符,你也可以使用'std :: cout'。但是'std ::'在一段時間後變成了一種反射。 – AxelOmega 2013-03-08 21:34:05