C++ 14从不同的构造函数(同一类)调用构造函数[具有不同的参数]

标签 c++ c++14

我今天写了一个程序,当它没有按照我的预期运行时,这让我非常头疼。

所以我写了一个简短的例子,它(几乎)*重现了这个问题。

我希望这在它应该做的事情上是相当不言自明的。

#include <iostream>

class A
{
    public:

    enum class defaults
    {
        DEFAULT_A
    };

    A(defaults default_val)
    {
        if(default_val == defaults::DEFAULT_A)
        {
            A("hello world");
        }
    }

    A(std::string str_)
    {
        str = str_;
        flag = true;
    }

    std::string getStr()
    {
        return str;
    }

    bool getFlag()
    {
        return flag;
    }

    private:

    bool flag;
    std::string str;

};

int main()
{

    A a(A::defaults::DEFAULT_A);

    std::cout << a.getStr() << std::endl;
    std::cout << a.getStr().size() << std::endl;
    if(a.getFlag())
    {
        std::cout << "true" << std::endl;
    }
    else
    {
        std::cout << "false" << std::endl;
    }

}

我的编译运行代码:g++ --std=c++14 main.cpp && ./a.out

编译/使用 gcc 版本 5.2.1 20151010 (Ubuntu 5.2.1-22ubuntu2)

输出:[带有行号]

1: 
2: 0
3: true

(第一行是空行。)

*与这个示例和我今天正在处理的代码唯一不同的是,我之前编写的代码中的标志是 false 而不是 true,但这仍然不是我所期望的 - 我期望它是 true。而且,该字符串不是空白的,但它确实包含“无意义的值”——至少不是我预期的那样。

我做错了什么?我猜这是非常明显的东西,但我就是看不出来。 (也许我一直在研究同一个问题太久了?)

编辑:

我可以这样做来解决问题吗?

A(defaults default_val)
{
    if(default_val == defaults::DEFAULT_A)
    {
        *this = A("hello world");
    }
}

最佳答案

要从另一个构造函数(委托(delegate)构造函数)调用构造函数,您需要在构造函数的初始化列表中进行:

       A(defaults default_val) : A("hello world") {
           .. more stuff to do after alling the delegate ctor

问题是这只允许您对委托(delegate) ctor 进行无条件调用(尽管您可以在参数中使用 ?: 来让他们值是有条件的。)无法有条件地调用委托(delegate)。

关于C++ 14从不同的构造函数(同一类)调用构造函数[具有不同的参数],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387418/

相关文章:

c++ - C++中的直接构造函数调用

c++ - b2 Shape 等于 0xCDCDCDCD,在 Create Fixture 时抛出异常

c++ - 通过 std::enable_if_t 传递被调用方法的返回值

c++ - 这是按什么顺序发生的

c++ - N4140 §8.2[dcl.ambig.res]/2 中的注释

c++ - 有没有办法在处理之前接收所有数据包?

c++ - 使用 Threads c++ 时套接字无法正确打开

c++ - XCode windows.h 和显示彩色文本

c++ - 查找值在 std::integer_sequence 中第一次出现的位置

c++ - 类型向量化的适当通用习惯用法?