gpt4 book ai didi

c++ - 在传递给参数时,为什么我不能在给定合适的构造函数的情况下隐式构造一个对象?

转载 作者:IT老高 更新时间:2023-10-28 23:10:48 26 4
gpt4 key购买 nike

在下面的例子中,为什么我不能简单地传递 stringprintFoo() ?

#include <string>
#include <iostream>

using namespace std;

class Foo {
public:
Foo(const Foo &foo) : str(foo.str) {}
Foo(string str) : str(str) {}

string str;
};

void printFoo(Foo foo) {
cout << foo.str << endl;
}

int main() {
Foo foo("qux");
printFoo(foo); // OK

printFoo("qix"); // error: no matching function for call to 'printFoo'

return 0;
}

无论出于何种原因,我都认为构造函数会自动确定并用于构造对象。

为什么我不能这样做,但我可以通过 char[n]接受 std::string 的参数的常量,例如?

最佳答案

将涉及两个隐式转换:

  1. std::string
  2. Foo

C++ 最多做一个:

来自 4 个标准转换 (N3337)

Standard conversions are implicit conversions with built-in meaning. Clause 4 enumerates the full set of such conversions. A standard conversion sequence is a sequence of standard conversions in the following order:

— Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion, and function-to-pointer conversion.

— Zero or one conversion from the following set: integral promotions, floating point promotion, integral conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to member conversions, and boolean conversions.

— Zero or one qualification conversion.

还有 12.3 次转换 (N3337)

1 Type conversions of class objects can be specified by constructors and by conversion functions. These conversions are called user-defined conversions and are used for implicit type conversions (Clause 4), for initialization (8.5), and for explicit type conversions (5.4, 5.2.9).

2 User-defined conversions are applied only where they are unambiguous (10.2, 12.3.2). Conversions obey the access control rules (Clause 11). Access control is applied after ambiguity resolution (3.4).

[...]

4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.

(强调我的)

关于c++ - 在传递给参数时,为什么我不能在给定合适的构造函数的情况下隐式构造一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790664/

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