2013-02-06 35 views
1

我有一個類Date。讓日期是:暴露字段的常量引用

class Date 
{ 
private: 
    unsigned int _day; 
    unsigned int _month; 
    unsigned int _year; 
public: 
    const unsigned int& Day; 
    const unsigned int& Month; 
    const unsigned int& Year; 

    Date() : Day(_day), Month(_month), Year(_year) 
    { } 
} 

出於某種原因,調用構造函數日,月,年後不點/參考_day,_month和_year。

我的一個猜測是他們在內存分配給類之前被設置,我將如何去解決這個問題(也就是在內存分配後設置引用)?

在此先感謝!

編輯:更多信息

_day(如爲)的值當我得到日的值不返回。我看到一個看似隨機的數字。

+0

你確定他們設置錯了嗎?什麼讓你有那個想法?請提供更多信息。 – StilesCrisis

+0

editted for more info –

回答

4

這是不是很清楚你想達到什麼。在Date類中,您可以直接訪問_date, _month, _year爲什麼要設置另一個參考?

但是,爲了回答你的問題

_day(如爲)的值當我得到日的值不返回。我得到一個看似隨機數

實際上,值正在返回,但你得到垃圾,因爲_day,_month和_year只是未初始化的整數。您需要在初始化列表中首先初始化它們:

Date() : _day(0), _month(1), _year(2), Day(_day), Month(_month), Year(_year) 
+0

_date,_month,_year無法訪問,因爲我不希望人們爲他們設置無效值。 const ref是提供一個可讀,簡單的接口來獲取字段中的信息(get和not edit)。嗯,讓我試試這個解決方案..我喜歡:) –

+0

現在很酷的作品:) tnx –

1

你應該使用返回const引用的getter來暴露它們,以避免存儲它們,它更方便。

class Date { 
private: 
    unsigned int _day; 
    unsigned int _month; 
    unsigned int _year; 

public: 
    const unsigned int& Day(){return _day;} 
    const unsigned int& Month(){return _month;} 
    const unsigned int& Year(){return _year;} 
} 
+0

我正在尋找這個事業它更漂亮。如果不能完成,我會照你說的去做,但我更喜歡這樣做。 –

+0

獲得者是傳統的C++語法。這些參考文件還具有每實例內存成本和性能成本。他們是一個糟糕的解決方案,只是爲了避免字符'()'。 – StilesCrisis

+0

在許多情況下,可讀性比在MAYBE微秒內可測量的不明顯的性能差異更重要。 –

0
Date::Date(unsigned int myDay, unsigned int myMonth, unsigned int myYear) 
{ 
    //Assign values here in constructor. 
} 

你可以寫不同的方法到類返回的日,月,或一年,或任何不同的日期格式它們的任意組合你已經在設計文檔中進行了計劃。

+0

Baptiste Wicht已經說過了。我正在尋找一種方法來完成這項工作。吸氣劑的可讀性較差。什麼是真正的原因(我只有一個猜測)的任何見解將是很好的:) –

+1

是的,他打敗了我7秒。 :D – Theo20185

+0

哈哈太慢了! :p –