2

我刚开始学习 C++,使用的是 Bjarne Stroustrap 的原著。这本书在其关于 Classes 的章节中,有一个创建具有以下接口的 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

4 回答 4

2

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

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

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

于 2013-06-08T06:51:50.417 回答
1

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

日期.cpp:

Date Date::default_date(1, 1, 1970);
于 2013-06-08T06:51:57.640 回答
0

首先,如果你应该使用默认构造函数,<code>static Date default_date; 会好的。

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

于 2013-06-08T11:29:33.880 回答
-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 */ }
于 2013-06-08T06:54:25.520 回答