从C ++ 17中的另一个构造函数调用具有不同参数类型的构造函数

红线

我有一个叫做日期的课:

class Date {
public:
    explicit Date(const int day = 1, const int month = 1, const int year = 0) {
        this->Construct(day, month, year);
    }

    explicit Date(const string &date_as_string) {
        int day, month, year;
        // parsing the string date_as_string
        this->Construct(day, month, year);
    }

private:
    void Construct(const int day, const int month, const int year) {
        // constructing the Date object
    }
};

有没有一种方法可以直接从Date(string&)调用Date(int,int,int),从而避免编写单独的函数?

UPD:

一些澄清。我的课应该像这样:

class Date {
public:
    explicit Date(const int day = 1, const int month = 1, const int year = 0) {
        // constructing the Date object
    }

    explicit Date(const string &date_as_string) {
        int day, month, year;
        // parsing the string date_as_string
        // call Date(day, month, year) to construct the Date object
    }

  // any other functions

private:
    // private fields
};

并应编译以下代码:

Date date("some_string_containing_date");
Date date(1, 1, 0);
Aschepler

是的,您可以定义另一个构造函数。不,我认为没有一些附加功能就无法做到。

调用同一类的另一个构造函数的构造函数称为“委托构造函数”,并且使用与成员初始值设定项列表相同的语法,但是使用类的自身名称而不是其基类和成员:

ClassName::ClassName(SomeParam1 p1, SomeParam2 p2)
    : ClassName(arg_expr1, arg_expr2, arg_expr3)
{ /* any other logic after the target constructor finishes */ }

但是由于需要中间对象,所以这种情况有些棘手date_as_struct或使用更新后的问题,只需要在输入另一个构造函数之前进行一些解析即可。我将通过制作一个额外的私有构造函数来解决这一问题,该构造函数采用Date_as_struct

class Date {
public:
    explicit Date(int day = 1, int month = 1, int year = 0); 
    explicit Date(const string &date_as_string);
    /* ... */
private:
    struct Date_as_struct {
        int day;
        int month;
        int year;
    };

    explicit Date(const Date_as_struct&);

    static Date_as_struct ParseStringContainingDate(const std::string&);
};

Date_as_structParseStringContainingDate在此声明为私有,因为听起来没有其他东西会真正使用它们。

然后对于字符串构造函数,您只需

Date::Date(const std::string& date_as_string)
    : Date(ParseStringContainingDate(date_as_string))
{}

Date(const Date_as_struct&)构造可以很容易授人以Date(int, int, int)反之亦然,无论是实际的成员初始化更自然。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

另一个元组构造函数中的C#元组解构函数

我可以在C ++中从另一个构造函数调用构造函数(构造函数链接)吗?

C#-经过一些计算后,从另一个构造函数调用一个构造函数

C ++:从另一个构造函数隐式调用构造函数

C ++-从另一个类构造函数调用一个类构造函数

C ++实例化对象,该对象在另一个没有指针的类构造函数中没有默认构造函数

C ++如何从具有一个参数的派生类构造函数调用具有两个参数的超类构造函数?

为什么从另一个构造函数内部调用的C ++构造函数不会修改类变量?

将具有不同数量参数的函数传递给另一个函数C ++

C ++将具有重载构造函数的对象添加到另一个对象

C ++-17:将函数指针转换为具有不同参数指针类型的函数

具有一个默认参数和一个变量参数的C ++构造函数

C#构造函数由于另一个构造函数而中断

在构造函数C ++中调用另一个对象的方法

具有可变数量和参数类型的C ++函数作为另一个函数的参数

调用另一个函数内具有参数类型的函数c#

C ++中不同参数的多个构造函数

另一个使用引用和参数的函数中的C ++调用函数

C ++中带有另一个模板类作为参数的构造函数

在C ++中,如何使构造函数具有不同类型的参数?

C ++:将一个对象复制到构造函数中的另一个对象

构造函数中的 C++ 语法错误 - 参数是对来自另一个类的对象的引用

我可以从 C# 中另一个类的构造函数调用构造函数吗?

C# 在另一个构造函数中使用构造函数

C++,在另一个对象构造函数中将对象作为参数传递

C++ 如何根据作为输入传递的参数调用一个构造函数或另一个构造函数?

稍后在 C++ 中的另一个类方法中调用类构造函数

如何在 C++ 中使用具有另一个类对象的构造函数?

找到一种在 C 中调用具有不同参数的函数的方法