string类型加减乘除

obe007 2013-12-22 04:22:23
有没有办法让用string类型定义的数字进行加减乘除,而不是相互连接呢;
#include<iostream>
#include<string>
using namespace std;
int main()
{
string a;
string s1, s2, s3, s4;
string sum;
system("pause>nul");
while (cin >> a)
{
/* if(!( || a.size()=13){ cout<<"不符合纯数字或长度"\ <<endl;
return -1; } */
for (size_t i = 6; i <= 9; ++i)
{
if (i == 6)
{
// s1(a[i]*1000);
}
if (i == 7)
{
s2 = a[i] * 100;
cout<<a[i]<<" "<<s2;
}
if (i == 8)
{
s3 = a[i] * 10;
}
if (i == 9)
{
s4 = a[i];
}
}
sum = s1 + s2 + s3 + s4;
string old("1995");
if (sum > old)
{
cout << "你的年龄未满18岁!" << endl;
}
else
{
cout << "已经满18岁勒" << endl;
}
}
return 0;
}
...全文
2088 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhcosin 2013-12-22
  • 打赏
  • 举报
回复
在 std 名字空间内重载 std::string 的 operator+() 函数很危险,因为这可能改变标准库的行为,如果你真的需要这个操作,你可以包装一下 std::string,提供一个自己的类,并为其写加法的重载.

class my_string
{
      std::string str;
public:
      my_string();
      my_string(const std::string &v_str);
public:
      friend const my_string operator+(const my_string &s1, const my_string &s2);
};
vipcxj 2013-12-22
  • 打赏
  • 举报
回复
引用 2 楼 vipcxj 的回复:

namespace std
{
   string operator + (const string & str1, const string & str2)
   {
      ...
   }
}
像这样重载,关键点在于你必须在命名空间std中重载,因为string是属于std的,其他就没什么特别的地方了
不过这样做是非常危险的,这样做改变了所有string的行为,之后将会很容易出错,所以还是自己专门写的函数,或者用个类封装string实现比较好。个人推荐第二种。

struct strnum
{
   std::string data;
   strnum(const std::string & _data) : data(_data) {}
   strnum operator + (const strnum & op2) const
   {
      ...
   }
}

之后直接使用strnum就行了
vipcxj 2013-12-22
  • 打赏
  • 举报
回复

namespace std
{
   string operator + (const string & str1, const string & str2)
   {
      ...
   }
}
像这样重载,关键点在于你必须在命名空间std中重载,因为string是属于std的,其他就没什么特别的地方了
Arnis1973 2013-12-22
  • 打赏
  • 举报
回复
自己写函数实现

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧