Const

// Const.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<iostream>

using namespace std;

const string &shortstring(const string& s1, const string& s2)
{
    return s1.size() < s2.size() ? s1 : s2;
}
string &shortstring(string &s1, string &s2)
{
    const string &r = shortstring(const_cast<const string&>(s1), const_cast<const string &>(s2));// auto &r = shortstring(const_cast<const string&>(s1), const_cast<const string &>(s2));
    return const_cast<string&>(r);
}

class ShortStr
{
public:
    ShortStr(const string &ss1,const string &ss2):s1(ss1),s2(ss2){}
    string shortstring()const{ return s1.size() < s2.size() ? s1 : s2; }
private:
    string s1, s2;
};

int main()
{
    string ss1 = "aaa";
    string ss2 = "aa";
    cout<< shortstring(ss1, ss2)<< endl;//返回string&

    const string ss3 = "bbb";
    const string ss4 = "bb";
    cout << shortstring(ss3, ss4)<< endl;//返回const string&

    ShortStr ss5("ccc", "cc");          //非常量版本对象
    cout << ss5.shortstring() << endl;

    const ShortStr ss6("ddd", "dd");    //常量版本对象
    cout << ss6.shortstring() << endl;

    return 0;
}

推荐阅读更多精彩内容