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

标签 c++ static

我刚刚开始学习 C++,使用的是 Bjarne Stroustrap 的原著。该书在有关类的章节中提供了一个创建具有以下接口(interface)的 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

如何处理此错误?
谢谢。

最佳答案

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

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

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

关于c++ - 在 C++ 中使用静态类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16996869/

相关文章:

c++ - 以静态大小的数组作为参数的通用 lambda

c++ - 具有恒定大小的 vector

C++ 动态分配数组,冒泡排序 + 求平均值

c++ - 比较BGR图像是否完全相同

java - 使用 Action 数据模型值在 Struts2 JSP 中调用静态方法帮助程序类

javascript - “await this.method();” 在静态方法中不起作用

java - 如何获取 Java Frame 对象以在 Reset 方法中使用?

javascript - Django 中的静态 html 页面

c++ - 如何避免模板类中typedef的重新定义?

c++ - 从可调用可变参数元组中的函数结果创建元组