华清远见23042 ,C++考试 编程题:自定义一个 string 类 , 要求添加相关函数的实现代码

自定义一个 string 类 , 要求添加相关函数的实现代码 。
class String
{
public:
String(const string (s); / / 构造函数
/ / 友元运算符重载
friend String operator +(const String &s1 const String &s2);
friend bool operator ==(const String &s1 ,const String &s2);
/ / 成员函数运算符
bool operator !=(const String &other);
/ / 类型转换重载
String& operator =(const String &s);
operator string(); / / 类型重载
/ / 成员函数
string get_str();
private:
string str;
}
#include <iostream>
#include <string>

using namespace std;

class String {
public:
    String(const string& s) : str(s) {} // 构造函数

    // 友元运算符重载
    friend String operator +(const String& s1, const String& s2);
    friend bool operator ==(const String& s1, const String& s2);

    // 成员函数运算符
    bool operator !=(const String& other);

    // 类型转换重载
    String& operator =(const String& s);
    operator string(); // 类型转换

    // 成员函数
    string get_str();

private:
    string str;
};

String operator +(const String& s1, const String& s2) {
    String result = s1.str + s2.str;
    return result;
}

bool operator ==(const String& s1, const String& s2) {
    return s1.str == s2.str;
}

bool String::operator !=(const String& other) {
    return str != other.str;
}

String& String::operator =(const String& s) {
    if (this != &s) {
        str = s.str;
    }
    return *this;
}

String::operator string() {
    return str;
}

string String::get_str() {
    return str;
}

int main() {
    String s1("Hello");
    String s2("World");

    String s3 = s1 + s2;
    cout << "s3: " << s3.get_str() << endl;

    if (s1 == s2) {
        cout << "s1 is equal to s2" << endl;
    } else {
        cout << "s1 is not equal to s2" << endl;
    }

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值