c++学习2011-03-07

来源:互联网 发布:最小二乘法矩阵推导 编辑:程序博客网 时间:2024/06/06 00:50

背景:
对象初始化

 

源代码:
#include <iostream>
using namespace std;

class complex        //定义一个复数
{
private:
 float real;     //实部
 float imag;     //虚部
public:
 complex(float r ,float i )
 {
  real = r;
  imag = i;
 } 
 complex operator + (complex c2);  //重载
  complex operator - (complex c2);  //重载
 void display();
};

complex complex::operator + (complex c2)
{
 return complex(real + c2.real,imag + c2.imag);
}

complex complex::operator - (complex c2)
{
 return complex(real - c2.real,imag - c2.imag);
}

void complex::display()
{
 cout << real << "," << imag << endl;
}

 

int main()
{
 complex c1(5.0,4.0),c2(2.0,10.0),c3; //c3没有初始化
        //正确初始化complex c1(5.0,4.0),c2(2.0,10.0),c3(0.0,0.0);
 c3 = c1 - c2;
 c3.display();
 c3 = c1 + c2;
 c3.display();
}

 

错误提示:
error: no matching function for call to 'complex::complex()'


错误分析:
没有初始化话对象

 

研究结果(知识扩展):
构造函数的作用就是在对象被创建时利用特定的值构造对象,将对象初始化为一个特定的状态

原创粉丝点击