下面的代码肯定可以运行。我的问题是我在类函数中分配了一些内存并返回一个指向它的指针。但在主函数中,我构建了一个新对象并为其指定了一个指针。但是如何释放返回的指针呢?我需要手动去做吗?如何避免C++中的类函数内存泄漏?
#include "stdio.h"
class Complex{
private:
float real;
float imaginary;
public:
Complex(float, float);
~Complex(void) {};
void set_real(float r);
void set_imaginary(float i);
float get_real();
float get_imaginary();
Complex* plus(Complex* another);
Complex* minus(Complex* another);
Complex* multiply(Complex* another);
};
Complex::Complex(float r, float i){
this->real = r;
this->imaginary = i;
}
void Complex::set_real(float r)
{this->real = r;}
void Complex::set_imaginary(float i)
{this->imaginary = i;}
float Complex::get_real()
{return real;}
float Complex::get_imaginary()
{return imaginary;}
Complex* Complex::plus(Complex* another){
Complex* result = new Complex(0,0);
result->set_real(this->real + another->real);
result->set_imaginary(this->imaginary + another->imaginary);
return result;
}
Complex* Complex::minus(Complex* another){
Complex* result = new Complex(0,0);
result->set_real(this->real - another->real);
result->set_imaginary(this->imaginary - another->imaginary);
return result;
}
Complex* Complex::multiply(Complex* another){
Complex* result = new Complex(0,0);
result->set_real((this->real * another->real) - (this->imaginary - another->imaginary));
result->set_imaginary((this->imaginary*another->real) + (this->real*another->imaginary));
return result;
}
int main(int argc, char* argv[]){
Complex* c = new Complex(3,4);
Complex* d = new Complex(6,9);
Complex* e = new Complex(0,0);
//will this line bring memory leak? Because all plus function already build a Complex object on leap. I don't know how to release it since I have to return it.
e = c->plus(d);
printf("result is %f + i%f", e->get_real(), e->get_imaginary());
delete c;
delete d;
delete e;
return 1;
}
我看到一个标题和代码,哪来的描述。哪里不对?什么是错误信息?你看到了什么?你期望看到什么? – 2012-02-06 19:31:57
你可以避免使用指针吗? – Karlson 2012-02-06 19:34:26