构造函数调用不明确 [英] Ambiguous constructor call

查看:53
本文介绍了构造函数调用不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的日期类,但是在主文件上出现错误,提示重载Date()的调用不明确."我不确定为什么,因为我认为只要构造函数具有不同的参数,我就可以了.这是我的代码:

I'm trying to create a simple date class, but I get an error on my main file that says, "call of overloaded Date() is ambiguous." I'm not sure why since I thought as long as I had different parameters for my constructor, I was ok. Here is my code:

头文件:

#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

and my 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

这两个参数都可以调用而没有参数.不能默认构造它,因为构造该对象的模棱两可.

These are both callable with no parameters. It can't be default constructed, because it's ambiguous how to construct the object.

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

Honestly, having those three with default parameters doesn't make much sense. When would I specify one but not the others?

这篇关于构造函数调用不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆