重载+运算符函数

本文介绍了一个C++程序实例,展示了如何将类成员函数s::connect用于字符串连接的功能改写为重载+运算符函数。通过这种方式,可以在不改变原有类结构的基础上实现更加直观的字符串拼接操作。

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

.阅读程序,其中s::connect函数实现字符串连接。把这个成员函数改写成重载+运算符函数,并修改main函数的对应代码,使其正确运行。

#include<iostream>

#include<cstring>

using namespace std;

class s{

public:

s(){*str='\0';len=0;}

s(char *pstr){

strcpy_s(str,pstr);len=strlen(pstr);}

char *gets(){return str;}

int getlen(){return len;}

    s operator+(s t);

private:

char str[100];

int len;

};

s s::operator+(s t)

{strcat(str,t.str);

return str;

}

void main(){

s obj1("visual"),obj2("c++"),obj3("language"),obj4;

obj4=obj1+obj2+obj3;

cout<<"obj4.str="<<obj4.gets()<<endl;

cout<<"obj4.len="<<obj4.getlen()<<endl;

getchar();

}

### 如何在编程语言中重载加(+运算符 #### 加运算符重载的概念 加运算符 `+` 是一种常见的二元运算符,在许多编程语言中可以用于执行数值相加或字符串拼接等操作。然而,对于用户定义的类型(如类),默认情况下无法直接使用该运算符。通过运算符重载技术,可以在某些支持此特性的编程语言(如 C++ 和 Python)中为自定义类型的对象赋予特定的行为。 #### 在 C++重载运算符 C++ 支持运算符重载,并允许开发者为类的对象定义 `+` 的行为。以下是具体方法: 1. **作为成员函数实现** 可以将 `operator+` 定义为类的一个成员函数。这种方式使得左操作数必须是当前类的对象。 ```cpp class Complex { double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 成员函数形式的 operator+ Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } void display() const { std::cout << "(" << real << ", " << imag << ")" << std::endl; } }; ``` 使用示例: ```cpp Complex c1(3, 2), c2(1, 7); Complex result = c1 + c2; // 调用 member function form of operator+ result.display(); // 输出 (4, 9) ``` 2. **作为友元函数实现** 如果希望任意一侧的操作数都可以是非本类的对象,则可以通过声明全局函数并将其设为类的友元来实现。 ```cpp class Complex { double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} friend Complex operator+(const Complex& lhs, const Complex& rhs); void display() const { std::cout << "(" << real << ", " << imag << ")" << std::endl; } }; Complex operator+(const Complex& lhs, const Complex& rhs) { return Complex(lhs.real + rhs.real, lhs.imag + rhs.imag); } ``` 使用示例: ```cpp Complex c1(3, 2), c2(1, 7); Complex result = c1 + c2; // 调用 global friend function form of operator+ result.display(); // 输出 (4, 9) ``` 注意:无论采用哪种方式,都应遵循一定的设计原则,确保重载后的运算符保持其原有的语义一致性[^4]。 #### 在 Python 中重载运算符 Python 同样支持运算符重载,可通过定义特殊的方法名 `_ _add_ _` 来实现对 `+` 运算符的支持。 ```python class Vector: def __init__(self, components): self.components = components def __add__(self, other): if len(self.components) != len(other.components): raise ValueError("Vectors must have the same dimension to add.") added_components = [x + y for x, y in zip(self.components, other.components)] return Vector(added_components) def __repr__(self): return f"Vector({self.components})" ``` 使用示例: ```python v1 = Vector([1, 2, 3]) v2 = Vector([4, 5, 6]) result = v1 + v2 # 调用了 __add__ 方法 print(result) # 输出: Vector([5, 7, 9]) ``` #### 需要注意的地方 - 不同的语言可能有不同的语法和限制条件; - 应始终考虑运算符重载的实际需求及其潜在风险,避免滥用造成代码难以理解的情况发生[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值