【发布时间】:2016-04-08 19:35:45
【问题描述】:
我对这个程序有 2 个问题:
为什么我不能使用标记为问题 1 的注释结构。调用复制构造函数而不是显式构造函数(据我所知,编译器调用构造函数的签名并没有歧义)。
对于在 QUESTION 2 分配的指针,我必须使用“delete []p”还是析构函数会自动删除它?
我是新来的课程,我正在努力掌握它,所以提前谢谢你。
#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
【问题讨论】:
-
你能把代码缩小一点吗?
-
好的,一秒钟。
-
任何时候使用
new,都需要有一个对应的delete;否则你会泄漏内存。 -
另外:不要使用
void main();它不是合法的 C++。请改用int main()。 -
好的,谢谢。我使用 void main() 是因为我在大学里这样做,而且我们使用的是 Visual Studio。(当我尝试在 Xcode 中编写一些 c++ 时,我确实注意到这是非法的)。
标签: c++ class constructor