Default constructor c++

前端 未结 4 2014
南笙
南笙 2021-01-07 04:19

I am trying to understand how default constructor (provided by the compiler if you do not write one) versus your own default constructor works.

So for example I wrot

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 05:04

    No there is not a different constructor.

    A n();
    

    is treated as a declaration of function taking no arguments and returning A object. You can see this with this code:

    class A
    {
    public:
        int x;
    
    public:
    
        A(){ std::cout << "Default constructor called for A\n";}
    
        A(int x){
    
            std::cout << "Argument constructor called for A\n";
    
            this->x = x;
    
        }
    };
    
    
    int main(int argc, char const *argv[])
    {
    
        A m;
        A p(0);
        A n();
        n.x =3;
    
        return 0;
    }
    

    The error is:

    main.cpp:129: error: request for member ‘x’ in ‘n’, which is of non-class type ‘A()’

提交回复
热议问题