十、操作符重载

一、使用c++标准库
c++标准库并不是c++语言的一部分
c++标准库是由c++语言编写而成的类库和函数的集合
c++标准库定义的类和对象都位于std的命名空间里
c++标准库的头文件都不带.h后缀
c++标准库涵盖了c库的功能
c库中

#include<cstdio>
using namespace std;
int main()
{
    printf("helloworld\n");
    printf("press any key to continu....");
    getchar();
    return 0;
}

c++标准库里的输入输出的类:
输出:cout(c++标准库里的显示器对象)
输入:cin(c++标准库里的键盘对象)

#include <iostream>//c++的输入输出标准库
using namespace std;
int main()
{
    cout<<"Hello World"<<endl;//endl作用是换行cout<<"Hello"<<endl<<" World"输出hello空一行在输出world
    int x;
    int y;
    cout<<"1st Parameter: ";
    cin>>x;//将键盘的输入右移到x中
    cout<<"2nd Parameter: ";
    cin>>y;//将键盘中的值也移到y中
    cout<<"Result: "<<x+y<<endl;//输出x+y的值
    return 0;
}

左移和右移在c语言中只能用于整数,并且语义是确定不变的
二、操作符重载
操作符重载为操作符提供不同的语义

#include <cstdlib>
#include <iostream>
using namespace std;
struct Complex
{
    int a;
    int b;
};
int main(int argc, char *argv[])
{
    Complex c1 = {1, 2};
    Complex c2 = {3, 4};
    Complex c3 = c1 + c2;//出现错误,结构体不能相加

    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

解决方法1:利用引用来求

#include<iostream>
#include<cstdlib>
using namespace std;
struct complax
{
    int a;
    int b;
};
complax add(const complax& a1, const complax a2)
{
    complax ret;
    ret.a = a1.a + a2.a;
    ret.b = a1.b + a2.b;
    return ret;
}
int main()
{
    complax t1 = {1, 3};
    complax t2 = {2, 5};
    complax t3;
    t3 = add(t1, t2);
    cout<<t3.a<<endl;
    cout<<t3.b<<endl;
    cin.get();
    return EXIT_SUCCESS;
}

add函数虽然可以解决complex变量相加的问题,但是complex在现实世界中是确实存在的复数,
并且复数在数学中的地位和普通的实数相同,那为什么不能让加操作符也支持复数相加呢

c++操作符重载的本质:
c++中通过operator关键字可以利用函数扩展操作符
operator的本质是通过函数重载实现操作符重载
如将上面的:
Complex add(const Complex& c1, const Complex& c2)//用引用
改成
Complex operator+ (const Complex& c1, const Complex& c2)//用引用

Complex c3 = add(c1, c2);
改成
Complex c3 = c1+c2;

用operator关键字扩展的操作符可以用于类吗?
三、c++中的友元:
private声明使得类的成员不能被外界访问
但是通过friend关键字可以例外的开发权限

include

include

using namespace std;

class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;//记得普通成员函数有一个指向类的指针
this->b = b;
}

int getA()
{
    return a;
}

int getB()
{
    return b;
}

friend Complex operator+ (const Complex& c1, const Complex& c2);//好朋友之间就没有什么秘密了

};

Complex operator+ (const Complex& c1, const Complex& c2)
{
Complex ret;

ret.a = c1.a + c2.a;
ret.b = c1.b + c2.b;

return ret;

}

int main(int argc, char *argv[])
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
//main表示complex的朋友,输出也会有问题
cout << “Press the enter key to continue …”;
cin.get();
return EXIT_SUCCESS;
}

解决方法:
重载的左移运算符:
ostream& operator<< (ostream& out, const Complex& c)//返回值按照c++库里的重载
{
out<

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值