string 相加
string str;
str="cc"+string("hello");
这里做了什么??
是否是:构造了一个string("cc"),然后和strign("hello")相加,然后再赋值
如果是的话,那么为什么会自动构造了一个string("cc")啊
[解决办法]
#include <iostream>
using namespace std;
class Test
{
friend Test operator+(int val, Test const& another);
friend Test operator+(Test const& another,int val);
friend ostream& operator<<(ostream& os, const Test& obj);
private:
int m_val;
public:
Test()
{
m_val=10;
}
public:
};
Test operator+(int val, Test const& another)
{
Test obj;
obj.m_val=val+another.m_val;
return obj;
}
Test operator+(Test const& another,int val)
{
Test obj;
obj.m_val=val+another.m_val;
return obj;
}
ostream& operator<<(ostream& os, const Test& obj)
{
cout << obj.m_val;
return os;
}
int main()
{
Test obj;
Test obj2;
obj2=2+obj;
cout << obj2 << endl;
return 0;
}