| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 402 人关注过本帖
标题:关于构造函数的一个问题
只看楼主 加入收藏
w378567402
Rank: 1
等 级:新手上路
帖 子:8
专家分:3
注 册:2008-3-11
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:1 
关于构造函数的一个问题
#include<iostream>
using namespace std;
class complex{
public:
complex(){real=0;imag=0;}
complex(double i,double j){real=i;imag=j;}
complex operator + (complex &t1);
complex operator - (complex &t1);
complex operator * (complex &t1);
complex operator / (complex &t1);
void display();
private:
double real;
double imag;
};
complex complex:: operator + (complex &t1)
{complex t2;
t2.real=real+t1.real;
t2.imag=imag+t2.imag;
return t2;
}
complex complex:: operator - (complex &t1)
{complex t2;
t2.real=real-t1.real;
t2.imag=imag-t2.imag;
return t2;
}
complex complex:: operator * (complex &t1)
{complex t2;
t2.real=real*t1.real;
t2.imag=imag*t2.imag;
return t2;
}
complex complex:: operator / (complex &t1)
{complex t2;
t2.real=real/t1.real;
t2.imag=imag/t2.imag;
return t2;
}
void complex::display()
{cout<<real<<"+"<<imag<<'i'<<endl;}
int main()
{complex t1(1,2),t2(3,4),t3;
t3=t1+t2;
cout<<"t1与t2之和是:";
t3.display();
t3=t1-t2;
cout<<"t1与t2之差是:";
t3.display();
t3=t1*t2;
cout<<"t1与t2之积是:";
t3.display();
t3=t1/t2;
cout<<"t1与t2之商是:";
t3.display();
return 0;
}
为什么这个题目的构造函数一定要有第一个呢?
我是一个c++的初学者,请大家帮帮忙啊!
搜索更多相关主题的帖子: 构造 函数 
2009-10-13 10:54
qq378166396
Rank: 2
等 级:论坛游民
帖 子:9
专家分:24
注 册:2009-8-25
收藏
得分:20 
第一个是不带参数的构造函数,第二个带参数

下面看一个例子
 #include<iostream.h>
 
class A{
private: int a;
 
public:
    A(int x){a=x;}
    void print(){cout<<"a="<<a<<endl;}
};
 
void main(){
A q(1);}
程序写到这一步,编译没有错误,但是如果将主函数的 A q(1)  换成A q;时  就出现了错误 error C2512: 'A' : no appropriate default constructor available
2009-10-13 13:22
快速回复:关于构造函数的一个问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014475 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved