在C ++中使用静态类成员

时间:2013-06-08 06:47:11

标签: c++ static

我刚开始学习C ++,使用了Bjarne Stroustrap的原着。本书在关于Clases的章节中有一个创建Date类的示例,该类具有以下接口:

#pragma once

#include <string>

class Date
{
public: //public interface:
    typedef
    enum Month{Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}
    Month;

    class Bad_date{ };  //exception class

    Date(int dd = 0, int mm = 1, int yy = 0);
    Date(int dd = 0, Month mm =Month(0), int yy =0); 
    //functions for examining the Date:
    int day() const;
    Month month() const;
    int year() const;
    std::string string_rep() const;     //string representation
    void char_rep(char s[]) const;      //C-style string representation

    static void set_default(int, Month, int);
    static Date default_date;
    //functions for changing the Date:
    Date& add_year(int n);          //add n years
    Date& add_month(int n);         //add n months
    Date& add_day(int n);           //add n days
private:
    int d, m, y;                //representation
    bool leapyear(int n);       //check if year is a leapyear. 
};

我需要帮助了解此类static Date default_date中静态成员的工作原理。在我的方法实现中,我使用变量,例如在构造函数的前几行

Date::Date(int dd, Month mm, int yy)
{

if(yy == 0)
    yy = default_date.year();
if(iNt mm == 0)
    mm = default_date.month();
if(dd == 0)
    dd = default_date.day();
        .
        .
        .
 }

当我调用构造函数时,编译时出现undefined reference to 'Date::default_date'错误。我在网上看到,这通常是在静态变量被幺化时引起的,所以我试着将变量声明为:

static Date default_date = 0; //or
static Date default_date = NULL;

这些声明中的任何一个都不起作用,它们都给我另一个错误

invalid in-class initialization of static data member of non-integral type 'Date'
'Date Date::default_date' has incomplete type

如何处理此错误?
谢谢。

4 个答案:

答案 0 :(得分:2)

你必须以这种方式定义变量:

Date Date::default_date(1, 1, 1980);

你应该将它放在.cpp文件中,而不是.h文件中,因为它是一个定义,如果它包含在头文件中,你可以多次定义它。 / p>

答案 1 :(得分:1)

从.cpp文件中的实现中删除static关键字,并避免将其初始化为0

Date.cpp:

Date Date::default_date(1, 1, 1970);

答案 2 :(得分:0)

首先,如果您应该使用默认构造函数,static Date default_date;就可以了。

第二,你应该初始化对象default_date,Date Date::default_date(1, 1, 1980);

答案 3 :(得分:-1)

// header
struct wtf{};
struct omg{ static wtf lol; /* declaration of lol */ };
// cpp
wtf omg::lol; // definition of lol

int main(){ omg().lol; /* test if you can instantiate omg and access lol */ }