Why can I not call my class's constructor from an instance of that class in C++?

前端 未结 10 1531
情深已故
情深已故 2021-01-03 16:39

When can an object of a class call the destructor of that class, as if it\'s a regular function? Why can\'t it call the constructor of the same class, as one of its regular

10条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 17:03

    you can invoke the constructor of an instance's class using typeof:

    class c
    {
    public:
       void add() ;
       c();
       ~c() ;
    };
    
    void main()
    {
     c objC  ;
     objC.add() ;
     objC.~c() ; // this line compiles (but is a bad idea)
     typeof objC otherObjC;  // so does this.
    }
    

    This does not affect the value of the instance objC, but creates a new instance otherObjC using objC's class constructor.

    Note: this may do something you don't expect if the static type is a baseclass of the dynamic type of the instance you have.

提交回复
热议问题