Question about c++ constructor.

Asked 2 years ago, Updated 2 years ago, 56 views

#include <iostream>

class A
{
    int x;

public:
    A(int c)
    {
        x = c;
        std::cout << "A(int c) is executed" << std::endl;
    }
    A(const A &a)
    {
        x = a.x;
        std::cout << "Create Copy" << std::endl;
    }
    void print_x()
    {
        std::cout << x << std::endl;
    }

};

int main()
{
    Aa2 = 10; // How does this sentence output the constructor A(intc) of class A?
    std::cout << "---------" << std::endl;
    a2.print_x();

}

I'm learning c++ grammar, but I have a question, so please ask me a question. If you compile this code and run it, In that code, Aa2 = 10; the sentence in the first line of the main function appears to output the constructor A(intc) of A... How is this possible?

From what I've learned, if you can call constructor A(intc)

A a2 = A(10);
A a2(10);

I learned that these two are possible, but aren't they? Please give me an answer me!!

c++ constructor

2022-09-21 10:56

1 Answers

In c++, a constructor with one parameter is called a "transformation constructor". A(int c) { x=c; } You've created a transformation generator.

And Aa2 = 10; by a transform generator whose compiler is defined in the syntax,

Aa2 = A(10); the compiler creates a temporary object in class A with a parameter of 10 and replaces it with a.

In other words, the int type, which is the data type of the parameter, can be converted to A class type by the transformation generator.


2022-09-21 10:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.