string类型加减乘除
有没有办法让用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;
}
[解决办法]
自己写函数实现
[解决办法]
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就行了
[解决办法]
在 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);
};