首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

string 相加解决思路

2013-02-02 
string 相加string strstrcc+string(hello)这里做了什么?? 是否是:构造了一个string(cc),然后和s

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;
}

热点排行