我刚刚开始学习 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/