第5章 函数

include "IOSTREAM"

using namespace std;

class Complex{
	friend ostream& operator << (ostream& out, const Complex& c);
	friend Complex operator- (const Complex& c1, const Complex& c2);
	//friend Complex operator* (const Complex& c1, const Complex& c2);
	//friend Complex operator/ (const Complex& c1, const Complex& c2);

public:
	Complex (double re = 0.0,double im = 0.0);
	Complex& operator+=(const Complex& c);
	Complex& operator-=(const Complex& c);

	Complex operator+(const Complex&c2);
private:
	double m_re,m_Im;
};

Complex& Complex::operator+=(const Complex& c)
{
	m_re += c.m_re;
	m_Im += c.m_Im;
	return *this;
}

Complex::Complex(double re, double im)
{
	m_re = re;
	m_Im = im;
}
Complex Complex::operator+(const Complex& c2)
{
	return Complex(m_re + c2.m_re, m_Im + c2.m_Im);
}

Complex& Complex::operator-=(const Complex& c)
{
	m_re -= c.m_re;
	m_Im -= c.m_Im;
	return *this;
}

ostream& operator << (ostream& out, const Complex& c)
{
	out << "(" << c.m_re << "," << c.m_Im << ")";
	return out;
}

Complex operator-(const Complex& c1, const Complex& c2)
{
	return Complex(c1.m_re -c2.m_re,c1.m_Im - c2.m_Im);
}

int main()
{
	/**/
	Complex c1 (4.5,1.2);
	Complex c2 (3.6,1.5);

	Complex c3 = c1 + c2;
	Complex c4 = c3 + 1.4;
	Complex c5 = 8.0 - c4;
	//Complex c6 = 1.2 + c4;

}
 

1。函数声明与函数定义之间有什么区别?
函数定义必须有函数主体,而且参数名称必须有。
函数声明没有主体,参数名称可有可无,但必须有类型,声明后还必须有分号。
2。为什么默认参数描述符出现在函数声明中而不在函数其定义中?
3。解释值传递和引用传递之间的区别,为什么使用其中一个而不使用另外一个?

不应该把较大的对象或者复制开销很大的对象通过值进行传递,因为创建零时拷贝将会消耗大量无必要的时间,机器周期和内存。
4。解释预处理宏与内联函数的区别。
内联函数和宏的区别在于,宏是由预处理器对宏进行替代,而内联函数是
通过编译器控制来实现的。而且内联函数是真正的函数,只是在需要用到的时
候,内联函数像宏一样的展开,所以取消了函数的参数压栈,减少了调用的开
销。你可以象调用函数一样来调用内联函数,而不必担心会产生于处理宏的一
些问题。
5。如果要针对Fraction对象重载算术运算符,成员函数与非成员全局运算符相比哪个更好?

运算符的重载:可以将运算符重载为成员函数,也可以重载为全局函数。这里首先注意到的不同将是调用方式的不同:成员运算符需要使用一个对象作为左侧的操作数,而相反的,全局函数则允许两个操作数采用相同的形式。

我们可以根据函数是否为const来对函数进行重载

#include "stdlib.h"
#include "iostream"
using namespace std;

class tgh
{
public:
    tgh():i(3){}
    const int a() const {return 5;}
    int a(){return i;}
protected:
    int i;
private:
};

void main()
{
    const tgh v;
    tgh s;
    const int i=s.a();
    int const j=s.a();
    printf("%d,%d",j,i);
    const int k = v.a();
    cout<<k<<endl; 
}

---------------------------------------------------------

#include "IOSTREAM"
using namespace std;

/*the left value can be changed*/
int& maxi(int& x,int& y){
	return (x > y) ? x : y;
}

int main(){
	int a = 10, b = 20;
	maxi(a, b) = 5;
	maxi(a, b) += 6;
	++maxi(a,b);
	cout << a << &apos;/t&apos;; << b << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的横打

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值