C ++:string运算符重载 [英] C++: string operator overload

查看:293
本文介绍了C ++:string运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以重载现有类中的现有函数/运算符吗?

Can I overload existing function/operator in existing class?

我试图做:

#include <iostream>
#include <string>
using namespace std;

string& string::operator<<(const string& str) {
  this->append(str);
}

但这会给我错误:

test.cpp:5: error: too few template-parameter-lists

我该如何做?或者我不能?

How can I do this? Or I can't?

推荐答案

不能向类添加成员函数,除非您修改该类的定义。请改用免费函数:

You can't add member functions to a class unless you modify that class' definition. Use a free function instead:

string& operator<<(string & lhs, const string & rhs) {
    return lhs += rhs;
}

这篇关于C ++:string运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆