class Complex {
public:
Complex( double real, double imaginary = 0 )错误[1],见下面1 : _real(real), _imaginary(imaginary) { }
void operator+ ( Complex other ) 错误[2],(此处存在两个问题)见下面2。 {
_real = _real + other._real;
_imaginary = _imaginary + other._imaginary; }
void operator<<( ostream os ) 错误[3],见下面3 {
os << \"(\" << _real << \ }
Complex operator++()错误[4],见下面4 {
++_real;
return *this; }
Complex operator++( int ) 错误[5],见下面5 {
Complex temp = *this; ++_real; return temp; }
private:
double _real, _imaginary; };
………………………………….…以下为修改后的程序…………………………………………. class Complex {
public:
explicit Complex( double real, double imaginary = 0 ) [1]此处构造函数加explicit,通知编译器不提供隐式转换。
{
real_(real);
imaginary_(imaginary);
}
Complex& operator+=( const Complex& other ) [2]要考虑用户的直觉,一般用+=去实现+, {
real_ += other.real_;
imaginary_ += other.imaginary_; return *this; }
Complex& operator++() [4]此处把返回值类型改为引用,是为了与return *this匹配。 {
++real_;
return *this; }
const Complex operator++( int )
[5]此处加const(使用户不能修改返回的参数),主要是为避免用户无意去修改,出现i++ ++这种连加的情况。 {
Complex temp( *this ); ++*this; return temp; }
ostream& Print( ostream& os ) const {
return os << \"(\" << real_ << \ }
friend const Complex operator+( const Complex& lhs, const Complex& rhs );[2]+必须重载为友元函数 friend ostream& operator<<( ostream& os, const Complex& c );
[3] 对于二元运算符(操作数有两个)如:+,<<,通常重载为友元函数而不是重载为成员函数。具体函数的实现在类外实现。 private:
double real_, imaginary_; };
const Complex operator+( const Complex& lhs, const Complex& rhs ) {
Complex ret( lhs );
ret += rhs;//会自动调用Complex& operator+=( const Complex& other ),实现两复数加。 return ret; }
ostream& operator<<( ostream& os, const Complex& c ) {
return c.Print(os); }
改错2、 class Array {
private:
int ptr[100]; public:
Array(const Array &init); ~Array(); };
Array::~Array() //析构函数 {
delete ptr; 此处错误,应改为delete []ptr,因为ptr类型为数组。 }
改错3、 Class Base {
Public: Base();
~Base();此处错误,应改为virtual ~Base(),用于基类指针来释放派生类对象时,为了能调到派生类的析构函数。如果此处不加虚析构函数,会造成派生
类的析构函数调不到,从而可能出现内存释放不掉。
}
Class A:public Base {
public: A(); ~A(); }
void main()
{
Base * p=new A;//使基类指针指向派生类对象 delete p;//通过释放基类指针来释放派生类对象 }
因篇幅问题不能全部显示,请点此查看更多更全内容