为什么在这里没有调用显式构造函数?

时间:2016-04-08 19:35:45

标签: c++ class constructor

我对这个程序有2个问题:

  1. 为什么我不能使用标记为QUESTION 1的注释结构。调用复制构造函数而不是显式构造函数(据我所知,编译器调用时签名不明确)构造函数)。

  2. 我是否必须使用"删除[] p"对于在问题2中分配的指针,还是析构函数会自动删除它?

  3. 我是班级的新手,我试图掌握它,所以提前谢谢你。

    #include <iostream>
    using namespace std;
    
    #define DIM 2
    
    class Complex {
    
        double re, im;
        char *name;
    
    public:
    
        Complex(double re = 1.0, double im = 1.0) {
    
            Complex::name = new char[9];
            Complex::re = re;
            Complex::im = im;
    
        }//constructor
    
        Complex(const Complex &aux) {
    
            re = aux.re;
            im = aux.im;
            name = aux.name;
    
        }//copy constructor
    
        void setReal(double re);
        void setImag(double im);
        void setName(char name[9]);
        double getReal();
        double getImag();
        char *getName();
        Complex sum(Complex);
        Complex dif(Complex);
        Complex multi(Complex);
        Complex div(Complex);
    
        ~Complex() {
    
        }//destructor
    
    };
    
    void main() {
    
        Complex *p = new Complex[DIM];  //QUESTION 2        
                                        //Is the destructor called or do I have do use delete []p ?
        char *name[DIM];
    
        for (int i = 0; i < DIM; i++) {
    
        //data input    
    
        }
    
        for (int i = 0; i < DIM; i++)       //freeing memory
    
            delete name[i];
    
        //Complex sum(), dif(), prod(), div();              //QUESTION 1
                                                            //why is this calling the copy constructor instead of the explicit 
                                                            //constructor with the deault parameters ?  
        Complex sum(*p), dif(*p), prod(*p), div(*p);    //initialising with the first element using copy constructor    
    
        for (int i = 1; i < DIM; i++) {
    
            sum=sum.sum(*(p+i));        
            dif = dif.dif(*(p + i));
            prod = prod.multi(*(p + i));
            div = div.div(*(p + i));
    
        }
    
    //some data output
    
        //delete[]p;
    
    }//end main
    

2 个答案:

答案 0 :(得分:2)

这一行:

Complex sum(), dif(), prod(), div();

未创建Complex变量sumdifproddiv。它实际上声明了4个不带参数的函数并返回Complex。声明如下:

Complex sum, dif, prod, div;

符合预期的

答案 1 :(得分:1)

对于第二个问题,您必须设置循环以删除每个对象的name成员变量,或者为您的类编写解构函数并使用delete []p

相关问题