gpt4 book ai didi

c++ - 当有多个构造函数时如何设置默认构造函数

转载 作者:行者123 更新时间:2023-11-30 01:55:55 28 4
gpt4 key购买 nike

我正在学习 C++ 中的构造函数,我知道您可以声明多个构造函数。您可以在下面看到我下面有 2 个 Date 构造函数,但我想将 Date(long) 设置为默认构造函数。有人可以解释一下我会怎么做吗?

好吧,显然上面的问题很有道理。我正在解决书中的一个问题,这就是它所说的:

Modify Program 10.3 so that the only data member of the class is a long integer named yyyymmdd. Do this by substituting the declaration long yyyymmdd; for these existing declarations:

int month; int day; int year;

Using the same constructor prototypes currently declared in the class declaration section, rewrite them so that the Date(long) method becomes the default constructor, and the Date(int, int, int) method converts a month, day, and year into the correct form for the class data members.

程序 10.3:

#include <iostream>
#include <iomanip>
using namespace std;

class Date
{
private:
int month, day, year;
public:
Date(int=7, int=4, int=2012);
Date(long);
void showDate();
};

Date::Date(int mm, int dd, int yyyy)
{
month = mm;
day = dd;
year = yyyy;
}

Date::Date(long yyyymmdd)
{
year = int(yyyymmdd/10000);
month = int( (yyyymmdd - year*10000)/100);
day = int(yyyymmdd - year*10000 - month*100);
}

void Date::showDate()
{
cout << "The date is "
<< setfill('0')
<< setw(2) << month << '/'
<< setw(2) << day << '/'
<< setw(2) << year % 100;
cout << endl;
}

int main()
{
Date a;
Date b(4,1,1998);
Date c = Date(20090515L);

a.showDate();
b.showDate();
c.showDate();
return 0;
}

最佳答案

您拥有的月/日/年构造函数的默认值使其成为默认构造函数(您可以不带参数调用它。您想要做的是取消这些默认值并将参数默认为 long 构造函数:

    Date(int, int, int);
Date(long = 20120704);

关于c++ - 当有多个构造函数时如何设置默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20221253/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com