4.特殊运算符重载

本文介绍了C++中如何定义和重载运算符,包括[]运算符用于访问数组元素的重载、赋值运算符重载以及仿函数的使用。同时讨论了标准输入输出流在C++中的应用和输出运算符重载示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1.operator是什么?

        在C++中,operator是一个关键字,用于定义或重载运算符的行为。运算符重载允许你为自定义类型(如类)重新定义或扩展运算符的行为。这允许对象像内置类型(如intdouble)那样使用运算符。


2.[ ]

        在C++中,[] 运算符通常用于访问数组或容器的元素。然而,这个运算符也可以被重载以用于自定义类型的对象。当你重载 [] 运算符时,你通常是在实现类似数组或集合的自定义类型,比如自定义的数组类、矩阵类或字符串类。

        重载 [] 运算符的常见方式是通过成员函数重载。这是因为当你使用 [] 运算符时,左边的对象通常是自定义类型的实例,而右边的对象或值则是你想要访问的索引。

#include <stdio.h>  
  
class Timer {  
public:  
    Timer() : hour(0), min(0), sec(0) {} //构造函数初始化 
    ~Timer() {}  //对象的生命周期结束时自动被调用,释放内存,结束调用
  
    void additTimer(int s) {  
        sec += s;  
        min += sec / 60;  
        sec %= 60;  
        hour += min / 60;  
        min %= 60;  
    }  
  
    void show() {  //函数打印
        printf("%02d:%02d:%02d\n", hour, min, sec);  
    }  
  
    int operator[](int a) {   // [ ]的引用
        switch (a) {  
            case 0:  
                return hour;  
            case 1:  
                return min;  
            case 2:  
                return sec;  
        }  
    }  
  
private:  
    int hour;  
    int min;  
    int sec;  
};  
  
int main(int argc, char *argv[]) {  
    Timer t;  
    t.additTimer(3);  
  
    printf("hour: %d\n", t[0]);  
    printf("min: %d\n", t[1]);  
    printf("sec: %d\n", t[2]);  
  
    return 0;  
}

 引用

#include <stdio.h>  
  
class Timer {  
public:  
    Timer() : hour(0), min(0), sec(0) {}  
    ~Timer() {}  
  
    // 添加时间(秒)  
    void addTimer(int s) {  
        sec += s;  
        min += sec / 60;  
        sec %= 60;  
        hour += min / 60;  
        min %= 60;  
    }  
  
    // 显示当前时间  
    void show() {  
        printf("%02d:%02d:%02d\n", hour, min, sec);  
    }  
  
    // 重载数组下标运算符,以便通过索引访问时、分、秒  
    int& operator[](int a) {  
        switch (a) {  
            case 0:  
                return hour;  
            case 1:  
                return min;  
            case 2:  
                return sec;  
        }  
    }  
  
private:  
    int hour;  // 小时  
    int min;   // 分钟  
    int sec;   // 秒  
};  
  
int main(int argc, char *argv[]) {  
    Timer t;  
    t.addTimer(3);  // 添加3秒  
    t.show();       // 显示当前时间  
  
    printf("hour: %d\n", t[0]); // 通过索引访问小时  
    printf("min: %d\n", t[1]);  // 通过索引访问分钟  
    printf("sec: %d\n", t[2]);  // 通过索引访问秒  
  
    // 下面的代码试图通过索引修改分钟的值,但原代码中存在未定义的变量t2  
    // 我们应该直接修改t的分钟值  
    t[1] = 30; // 设置分钟为30  要在 operator[]函数前加引用
  	t.show();       // 显示当前时间  
    printf("hour: %d\n", t[0]); // 再次通过索引访问小时  
    printf("min: %d\n", t[1]);  // 再次通过索引访问分钟  
    printf("sec: %d\n", t[2]);  // 再次通过索引访问秒  
  
    return 0;  
}

3.=

赋值运算符重载

#include <stdio.h>
#include <string.h>
class A{
public:	
	A()
	{		
		printf("A()\n");
		p = new char[10];
		strcpy(p, "hello");	
		printf("p: %s\n", p);	
		printf("p: %s\n", this->p);
	}	
	A(const A &x)	
	{		
		printf("A(const A &x)\n");	
		p = new char[10];		
		strcpy(p, x.p);		
		}	
	~A()	
	{	
		printf("~A()\n");		
		delete [] p;
	}	
	A&  operator=(A &x)
		{		
			printf("operator=\n");
			p = new char[10];	
			strcpy(p, x.p);		
			return *this;	
		}
private:
		char *p;
};
int main()
{	
	A x;
	A y = x;	
	y = x;
}

4.()

仿函数

#include <iostream>
/**汇率转换**/
using namespace std;

class Converter{
public:
		Converter(double rate)	{
            //将传递给构造函数的 rate 参数的值赋给当前对象的 rate 成员变量。
			this->rate = rate;		
        }

		~Converter(){}		

		double operator()(double RMB)
		{
			return RMB*rate;
		}
private:
	double rate;
};

double RMBto(double RMB,double rate)
{
	return RMB*rate;
}

int main()
{	
	Converter RMBtoUS(1.1);
	cout << RMBtoUS(10) <<endl;
	Converter RMBtoE(1.2);
	cout << RMBtoE(10) <<endl;
}

5.<<

  • << 是一个插入运算符,用于将数据插入到输出流中。
  • std::cout 是一个C++标准库中的输出流对象,用于将数据发送到标准输出设备(通常是控制台)。
  • std::endl 是一个流操纵符,它执行两个操作:首先,它输出一个换行符('\n'),然后刷新输出流。这意味着任何缓冲在 std::cout 中的数据都会被立即发送到控制台。

#include <iostream>是C++标准库中的一个文件,它定义了用于输入/输出流的对象,如std::coutstd::cin

#include <iostream>

int main()
{	
	std::cout << "hello"<<std::endl; //用于在控制台上输出文本。
}

 using namespace std; 声明了使用std命名空间,这样我们就可以直接使用coutendl等名称,而不必每次都写std::coutstd::endl

#include <iostream>
using namespace std; 
int main()
{	
	cout << "hello"<<endl;
}

 输出运算符重载

#include <stdio.h>  
#include <iostream>

using namespace std;

class Timer {  
public:  
    Timer() : hour(0), min(0), sec(0) {}  
    ~Timer() {}  
  
    // 添加时间(秒)  
    void addTimer(int s) {  
        sec += s;  
        min += sec / 60;  
        sec %= 60;  
        hour += min / 60;  
        min %= 60;  
    }  
  
    // 显示当前时间  
    void show() {  
        printf("%02d:%02d:%02d\n", hour, min, sec);  
    }  
  
    // 重载数组下标运算符,以便通过索引访问时、分、秒  
    int& operator[](int a) {  
        switch (a) {  
            case 0:  
                return hour;  
            case 1:  
                return min;  
            case 2:  
                return sec;  
        }  
    } 
	friend ostream &operator<<(ostream &out, const Timer &t);
  
private:  
    int hour;  // 小时  
    int min;   // 分钟  
    int sec;   // 秒  
};  

ostream &operator<<(ostream &out, const Timer &t)
{	
	out << "hour: "<<t.hour << " min: "<<t.min<<" sec: "<<t.sec<< endl;
}
int main(int argc, char *argv[]) {  
    Timer t;  
    t.addTimer(3);  // 添加3秒  
    t.show();       // 显示当前时间  

	cout << t;
	
  
    return 0;  
}

6.标准输入输出流

C语言中的写法

#include <stdio.h>
#include <string.h>

int main()
{
	
	char buf[100];
	printf("Input:");fflush(stdout);

	if (fgets(buf, sizeof(buf), stdin) != NULL) 
	{           
		buf[strcspn(buf, "\n")] = 0;     // 移除可能存在的换行符     
		printf("%s\n", buf);      
	} else {   
		printf("Failed to read input.\n");    
	}  

}

C++中的写法

#include <stdio.h>
#include <iostream>

using namespace std;
int main()
{
	
	char buf[100];
	cout << "Input:";  //printf("Input:");fflush(stdout);

	cin >> buf; //fgets(buf, sizeof(buf), stdin)

	cout << buf << endl; //printf("%s\n", buf);
}
#include <stdio.h>
#include <iostream>

using namespace std;
int main()
{
	
	cout << 10 << endl; //printf("10\n");

	cout << hex << 10 << endl; //打印10的16进制
}
#include <stdio.h>
#include <iostream>

int main()
{
	std::cout << 10 << std::endl; //printf("10\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值