C++ 隐式转换

标签 c++

对我最近的回答 What other useful casts can be used in C++ 的一些评论,说明我对C++转换的理解是错误的。为了澄清问题,请考虑以下代码:

#include <string>

struct A {
    A( const std::string & s ) {}
};

void func( const A & a ) {
}

int main() {
    func( "one" );                  // error
    func( A("two") );           // ok
    func( std::string("three") );   // ok
}

我的断言是第一个函数调用是错误的,因为没有从 const char * 到 A 的转换。有从字符串到 A 的转换,但是使用它会涉及多个转换.我的理解是这是不允许的,这似乎得到了 g++ 4.4.0 和 Comeau 编译器的证实。使用 Comeau,我收到以下错误:

"ComeauTest.c", line 11: error: no suitable constructor exists 
      to convert from "const char [4]" to "A"
      func( "one" );                    // error

如果你能指出我错了,无论是在这里还是在原始答案中,最好是引用 C++ 标准,请这样做。

而 C++ 标准的答案似乎是:

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

感谢 Abhay 提供报价。

最佳答案

我认为尖牙的回答很准确。标题为“转换”的 C++ 标准 (SC22-N-4411.pdf) 第 12.3.4 节明确规定只允许一种隐式用户定义转换。

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).

3 [ Note: See 13.3 for a discussion of the use of conversions in function calls as well as examples below. —end note ]

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/867462/

相关文章:

c++ - 在 Visual Studio 上运行时程序变慢

c++ - 客户端服务器消息解释

c++ - 使用 boost::math::ibeta 时出错

c++ - 使用带有 shared_ptr 的 Clang 线程安全分析

c++ - 当作为 Function 的参数传递给线程时,为什么仿函数的 dtor 调用两次(多次)?

java - 我们需要Java++吗?

c++ - 写入内存缓冲区时的性能损失 (C++)

c++ - 我在练习 LeetCode 时遇到了一些奇怪的错误

c++ - 从 C++ 中的接口(interface)名称获取 IID? (VS 2010 自动化)

c++ - 从给定 vector 的 block 中生成新 vector