c++ - 不明确的构造函数调用

标签 c++ constructor

我正在尝试创建一个简单的日期类,但我在主文件中收到一条错误消息:“重载 Date() 的调用不明确。”我不确定为什么因为我认为只要我的构造函数有不同的参数,我就可以了。这是我的代码:

头文件:

#ifndef DATE_H
#define DATE_H
using std::string;

class Date
{
public:
    static const int monthsPerYear = 12; // num of months in a yr
    Date(int = 1, int = 1, int = 1900); // default constructor
    Date(); // uses system time to create object
    void print() const; // print date in month/day/year format
    ~Date(); // provided to confirm destruction order
    string getMonth(int month) const; // gets month in text format
private:
    int month; // 1 - 12
    int day; // 1 - 31 
    int year; // any year

    int checkDay(int) const;
};

#endif

.cpp文件

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include "Date.h"
using namespace std;

Date::Date()
{
    time_t seconds = time(NULL);
    struct tm* t = localtime(&seconds);
    month = t->tm_mon;
    day = t->tm_mday;
    year = t->tm_year;
}

Date::Date(int mn, int dy, int yr)
{
    if (mn > 0 && mn <= monthsPerYear)
        month = mn;
    else
    {
        month = 1; // invalid month set to 1
        cout << "Invalid month (" << mn << ") set to 1.\n";
    }

    year = yr; // could validate yr
    day  = checkDay(dy); // validate the day

    // output Date object to show when its constructor is called
    cout << "Date object constructor for date ";
    print();
    cout << endl;
}

void Date::print() const
{
    string str;
    cout << month << '/' << day << '/' << year << '\n';

    // new code for HW2
    cout << setfill('0') << setw(3) << day;  // prints in ddd
    cout << " " << year << '\n';             // yyyy format

    str = getMonth(month);

    // prints in month (full word), day, year
    cout << str << " " << day << ", " << year << '\n';
}

和我的 main.cpp

#include <iostream>
#include "Date.h"
using std::cout;

int main()
{
    Date date1(4, 30, 1980);
    date1.print();
    cout << '\n';

    Date date2;
    date2.print();


}

最佳答案

Date(int = 1, int = 1, int = 1900); // default constructor
Date(); // uses system time to create object

这些都可以不带参数调用。它不能被默认构造,因为如何构造对象是不明确的。

老实说,让这三个具有默认参数没有多大意义。我什么时候指定一个而不指定其他的?

关于c++ - 不明确的构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2673687/

相关文章:

c++ - 具有重叠 I/O 的 FILE_FLAG_NO_BUFFERING - 字节读为零

c++ - 使用指针算法时内存泄漏

javascript - 如何在其内部引用 Backbone/Marionette View ?

java - 恢复某些字段标记为 transient 的状态

c++ - 执行用C++编写的.exe问题(使用mingw编译器)

c++ - 为什么cin.get()卡在换行符上?

c++ - 为什么不使用 boost::optional 作为更好的 scoped_ptr

c++ - 为什么带有花括号初始化器列表的构造函数/虚拟析构函数不起作用?

C# 备用无参数构造函数

c++ - 使用相同的参数名称和成员名称是否有效