使用 std::string 和 char* 的最令人烦恼的解析实例

Instance of Most Vexing Parse with std::string and char*

这是我上一个问题的后续问题: 我从中了解了最令人烦恼的解析。

我现在明白了问题的要点,但是有一个语法遗留项我仍然不太明白,我想作为一个独立的问题来问,因为之前的讨论 post 越来越长了。

鉴于此代码:

#include <iostream>
#include <string>

class Foo
{
    public:
        Foo(double d)
            : mD(d)
        {
        }

        Foo(const std::string& str)
        {
            try
            {
                mD = std::stod(str);
            }
            catch (...)
            {
                throw;
            }
        }

        Foo(const Foo& other)
            : mD(other.mD)
        {
        }

        virtual ~Foo() {}

    protected:
        double mD;
};

class Bar
{
    public:
        Bar(const Foo& a, const Foo& b)
            : mA(a)
            , mB(b)
        {
        }

        virtual ~Bar() {}

    protected:
        Foo mA;
        Foo mB;
};

int main(int argc, char* argv[])
{
    if (argc < 3) { return 0; }

    Foo a(std::string(argv[1]));
    Foo b(std::string(argv[2]));

    Bar wtf(a, b);
}

我现在明白,Foo a(std::string(argv[1])); 行可以解释为:

(1) 创建一个名为 a 的 Foo 和一个用 char* 创建的匿名 std::string。 (我想要的解释)

(2) 名为 a 的函数的声明(不是 定义 )接受 std::string*.

从原问题的答案中,我了解到可以在另一个函数的范围内声明函数。这对我来说是新的,但似乎在情理之中,我可以买它。

不过,我无法理解的是将 std::string(argv[1]) 解释为 std::string*

argv[1] 是一个 char*,所以我仍然不明白为什么该行没有被解释为用 char* 构造的匿名 std::string。毕竟,我已经使用了与以下类似的代码数百次,而没有仔细检查这是否会导致除了使用其 char* 构造函数构造 std::string 之外的任何结果:

#include <iostream>
int main()
{
    char* pFoo[] = {"foo"};
    std::string str(pFoo[0]);
    std::cout << str << std::endl;
    return 0;
}

我即将理解最棘手的解析问题;如果有人可以进一步解释这最后一个琐碎的部分,那可能会帮助我超越边缘。

谢谢。

Foo a(std::string(argv[1]));

声明了一个名为 a 的函数,它 returns Foo 并且有一个类型为 std::string[1] 的参数(名为 argv)。由于数组函数参数总是替换为指针参数,因此函数参数的实际类型变为std::string*.