Home > Backend Development > C++ > body text

Why does `func(\'one\')` cause an error in C implicit conversions?

Mary-Kate Olsen
Release: 2024-11-01 05:36:02
Original
373 people have browsed it

Why does `func(

C Implicit Conversions

In the context of C , the concept of implicit conversions has been a subject of discussion. A recent answer on "What other useful casts can be used in C ?" raised questions about the correct understanding of conversions in C .

Consider the following code snippet:

<code class="cpp">#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
}</code>
Copy after login

In this snippet, the first function call, func("one"), results in an error. This is because there is no direct conversion from a const char * to an A. While there is a conversion from a string to an A, using it would involve multiple implicit conversions, which is not permitted according to C standards.

The C Standard (SC22-N-4411.pdf) in section 12.3.4 "Conversions" states:

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

This means that only one implicit user-defined conversion can be applied when performing a conversion. In the first function call, both the conversion from const char * to string and the conversion from string to A are user-defined conversions. Since more than one conversion is required, the compiler raises an error.

The above is the detailed content of Why does `func(\'one\')` cause an error in C implicit conversions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!