我有课程日期和时间。我正在使用公共构造函数创建一个 Onetime 类,但我不确定如何创建一个新的内联日期和时间。
schedule[0]= new Onetime("see the dentist",
Date(2013, 11, 4),
Time(11, 30, 0),
Time(12, 30, 0));
class Onetime {
public:
Onetime( // what should I put here? )
}
我有课程日期和时间。我正在使用公共构造函数创建一个 Onetime 类,但我不确定如何创建一个新的内联日期和时间。
schedule[0]= new Onetime("see the dentist",
Date(2013, 11, 4),
Time(11, 30, 0),
Time(12, 30, 0));
class Onetime {
public:
Onetime( // what should I put here? )
}
This the standard approach
class Onetime {
std::string description;
Date date;
Time from_time;
Time to_time;
Onetime(const std::string& description,
const Date& date,
const Time& from_time,
const Time& to_time)
: description(description),
date(date),
from_time(from_time),
to_time(to_time)
{
... rest of initialization code, if needed ...
}
...
};
使用Date
andTime
或const Date &
andconst Time &
作为日期和时间参数来声明类。通常const &
适用于大型对象,以防止它们被不必要地复制。小物件可以用const &
也可以不用,随你喜欢。
// Onetime.h
class Onetime {
public:
Onetime(const std::string &description,
const Date &date,
const Time &startTime,
const Time &endTime);
private:
std::string description;
Date date;
Time startTime, endTime;
};
.cpp
然后在文件中定义构造函数。用于:
表示初始化列表以初始化成员变量。
// Onetime.cpp
Onetime::Onetime(const std::string &description,
const Date &date,
const Time &startTime,
const Time &endTime)
: description(description),
date(date), startTime(startTime), endTime(endTime)
{
}
最后,您可以Onetime
完全按照您编写的方式创建一个对象。如果您愿意,您甚至可以省略new
关键字。new
用于在堆上分配对象,在 C++ 中您并不总是需要这样做(例如,与 Java 或 C# 不同)。
schedule[0] = new Onetime("see the dentist",
Date(2013, 11, 4),
Time(11, 30, 0),
Time(12, 30, 0));
You can do,
class Onetime {
public:
Onetime(const std::string& message, const Date& date, const Time& start, const Time& end);
private:
std::string m_message;
Date m_date;
Time m_start;
Time m_end;
}
and
Onetime::Onetime(const std::string& message, const Date& date, const Time& start, const Time& end)
: m_message(message), m_date(date), m_start(start), m_end(end)
{
}
Try to avoid new
as that is heap-allocated memory and expensive to get (compared to stack-based memory.)