Home Backend Development C#.Net Tutorial What is C++ implicit type conversion?

What is C++ implicit type conversion?

Jul 24, 2020 am 10:59 AM
c++ implicit type conversion

Implicit type conversion in C refers to a compiler's automatic conversion from "constructor parameter type" to "class type". Implicit class type conversion brings risks. Implicit conversion results in temporary variables of the class, which disappear after the operation is completed. We constructed an object that was discarded after completing the test.

What is C++ implicit type conversion?

C implicit class type conversion

In "C Primer" Mentioned:

"A constructor that can be called with a single parameter defines an implicit conversion from the parameter type to the class type."

It should be noted here that "can be called with a single formal parameter" does not mean that the constructor can only have one formal parameter, but that it can have multiple formal parameters, but those formal parameters have default actual parameters. .

So, what is "implicit conversion"? As the above sentence also says, is a compiler's automatic conversion from the constructor parameter type to the class type.

Let’s take a look through the code:

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std ;
class BOOK  //定义了一个书类
{
    private:
        string _bookISBN ;  //书的ISBN号
        float _price ;    //书的价格

    public:
        //定义了一个成员函数,这个函数即是那个“期待一个实参为类类型的函数”
        //这个函数用于比较两本书的ISBN号是否相同
        bool isSameISBN(const BOOK & other ){
            return other._bookISBN==_bookISBN;
                }

        //类的构造函数,即那个“能够用一个参数进行调用的构造函数”(虽然它有两个形参,但其中一个有默认实参,只用一个参数也能进行调用)
        BOOK(string ISBN,float price=0.0f):_bookISBN(ISBN),_price(price){}
};

int main()
{
    BOOK A("A-A-A");
    BOOK B("B-B-B");

    cout<<A.isSameISBN(B)<<endl;   //正经地进行比较,无需发生转换

    cout<<A.isSameISBN(string("A-A-A"))<<endl; //此处即发生一个隐式转换:string类型-->BOOK类型,借助BOOK的构造函数进行转换,以满足isSameISBN函数的参数期待。
    cout<<A.isSameISBN(BOOK("A-A-A"))<<endl;    //显式创建临时对象,也即是编译器干的事情。
    
    system("pause");
}

As you can see in the code, the isSameISBN function is expecting a BOOK class type parameter, but we passed a string type Give it to it, this is not what it wants! Fortunately, there is a constructor in the BOOK class, which is called with a string type actual parameter. The compiler calls this constructor, implicitly converts the string type to the BOOK type (constructs a BOOK temporary object), and then passes it Give the isSameISBN function.

Implicit class type conversion still brings risks. As marked above, implicit conversion obtains temporary variables of the class and disappears after completing the operation. We construct an object that is discarded after completing the test.

We can suppress this conversion through explicit declaration:

explicit BOOK(string ISBN,float price=0.0f):_bookISBN(ISBN),_price(price){}

The explicit keyword can only be used for constructor declarations inside the class. In this way, the BOOK class constructor cannot be used Since the object is created implicitly, when compiling the above code, the following prompt will appear:

What is C++ implicit type conversion?

Now the user can only perform display type conversion and explicitly create temporary objects.

To summarize:

  • can be called with one actual parameter, which does not mean that the constructor can only have one formal parameter.

  • Implicit class type conversion is easy to cause errors. Unless you have a clear reason to use implicit class type conversion, otherwise, declare all constructors that can be called with one argument as explicit. .

  • explicit can only be used for declaration of constructors inside a class. Although it can avoid the problems caused by implicit type conversion, it requires the user to explicitly create temporary objects (which imposes requirements on the user).

Recommended: "C Tutorial"

The above is the detailed content of What is C++ implicit type conversion?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1545
276
Succinct (PROVE Coin) Price Forecast: 2025, 2026, 2027-2030 Succinct (PROVE Coin) Price Forecast: 2025, 2026, 2027-2030 Aug 11, 2025 am 10:12 AM

Directory What is Succinct (PROVE) Which venture capital supports Succinct (PROVE)? How Succinct (PROVE) Working Principle SP1zkVM and Prover Network OPSuccinct Technology Cross-chain Verification PROVE Token Economics Token Details 2025, 2026, 2027-2030 Succinct (PROVE) Price Forecast Succinct (PROVE) Price Forecast Succinct (PROVE) Price Forecast: Trading Volume Expansion and Listing Momentum 2025-20

What should I do if the application cannot start normally (0xc0000906)? See the solution here What should I do if the application cannot start normally (0xc0000906)? See the solution here Aug 13, 2025 pm 06:42 PM

When opening the software or game, a prompt suddenly appears that "the application cannot start normally (0xc0000906)" appears, and many users will be confused and don't know where to start. In fact, most of these errors are caused by corruption of system files or missing runtime libraries. Don't rush to reinstall the system. This article provides you with several simple and effective solutions to help you quickly restore the program to run. 1. What is the error of 0xc0000906? Error code 0xc0000906 is a common startup exception in Windows systems, which usually means that the program cannot load the necessary system components or running environment when running. This problem often occurs when running large software or games. The main reasons may include: the necessary runtime library is not installed or damaged. The software installation package is endless

C   memory order relaxed example C memory order relaxed example Aug 08, 2025 am 01:00 AM

memory_order_relaxed is suitable for scenarios where only atomicity is required without synchronization or order guarantee, such as counters, statistics, etc. 1. When using memory_order_relaxed, operations can be rearranged by the compiler or CPU as long as the single-threaded data dependency is not destroyed. 2. In the example, multiple threads increment the atomic counter, because they only care about the final value and the operation is consistent, the relaxed memory order is safe and efficient. 3. Fetch_add and load do not provide synchronization or sequential constraints when using relaxed. 4. In the error example, the producer-consumer synchronization is implemented using relaxed, which may cause the consumer to read unupdated data values because there is no order guarantee. 5. The correct way is

How to get the size of a file in C How to get the size of a file in C Aug 11, 2025 pm 12:34 PM

Use the seekg and tellg methods of std::ifstream to obtain file size across platforms. By opening a binary file and positioning it to the end, use tellg() to return the number of bytes; 2. It is recommended to use std::filesystem::file_size for C 17 and above. The code is concise and errors are handled through exceptions. The C 17 standard must be enabled; 3. On POSIX systems, the stat() function can be used to efficiently obtain file size, which is suitable for performance-sensitive scenarios. The appropriate method should be selected based on the compiler and platform, and std::filesystem should be used first (if available), otherwise use ifstream to ensure compatibility, or use st on Unix systems

How to use regular expressions in C How to use regular expressions in C Aug 12, 2025 am 10:46 AM

To use regular expressions in C, you need to include header files and use the functions it provides for pattern matching and text processing. 1. Use std::regex_match to match the full string, and return true only when the entire string conforms to the pattern; 2. Use std::regex_search to find matches at any position in the string; 3. Use std::smatch to extract the capture group, obtain the complete match through matches[0], matches[1] and subsequent sub-matches; 4. Use std::regex_replace to replace the matching text, and support the capture group with references such as $1 and $2; 5. You can add an iset when constructing the regex (

How to fix missing MSVCP71.dll in your computer? There are only three methods required How to fix missing MSVCP71.dll in your computer? There are only three methods required Aug 14, 2025 pm 08:03 PM

The computer prompts "MsVCP71.dll is missing from the computer", which is usually because the system lacks critical running components, which causes the software to not load normally. This article will deeply analyze the functions of the file and the root cause of the error, and provide three efficient solutions to help you quickly restore the program to run. 1. What is MSVCP71.dll? MSVCP71.dll belongs to the core runtime library file of Microsoft VisualC 2003 and belongs to the dynamic link library (DLL) type. It is mainly used to support programs written in C to call standard functions, STL templates and basic data processing modules. Many applications and classic games developed in the early 2000s rely on this file to run. Once the file is missing or corrupted,

C   operator overloading example C operator overloading example Aug 15, 2025 am 10:18 AM

Operator overloading in C allows new behaviors of standard operators to be assigned to custom types, 1. Return new objects through member function overloading; 2. Overload = Modify the current object and return reference; 3. Friend function overloading

How to write a basic Makefile for a C   project? How to write a basic Makefile for a C project? Aug 15, 2025 am 11:17 AM

AbasicMakefileautomatesC compilationbydefiningruleswithtargets,dependencies,andcommands.2.KeycomponentsincludevariableslikeCXX,CXXFLAGS,TARGET,SRCS,andOBJStosimplifyconfiguration.3.Apatternrule(%.o:%.cpp)compilessourcefilesintoobjectfilesusing$

See all articles