gpt4 book ai didi

c++ - 使用 std::string 和 char* 的最烦人的解析实例

转载 作者:太空狗 更新时间:2023-10-29 20:54:28 33 4
gpt4 key购买 nike

这是我之前问题的后续问题:C++ compile error constructing object with rvalue std::string从中我了解了最令人烦恼的解析。

我现在明白了问题的要点,但是还有一个语法项我还是不太明白,我想把它作为一个独立的问题来问,因为上一篇文章的讨论已经很长了.

给定这段代码:

#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匿名 std::stringchar* 创建的. (我想要的解释)

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

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

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

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

#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 的函数,该函数返回 Foo 并具有一个类型为 std::string[ 的参数(名为 argv) 1]。由于数组函数参数总是替换为指针参数,因此函数参数的实际类型变为 std::string*

关于c++ - 使用 std::string 和 char* 的最烦人的解析实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39046314/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com