注册 登录
编程论坛 C++教室

为一个类定义一个<运算符的问题?急!!!

忠犬八公 发布于 2014-04-12 16:46, 494 次点击
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class HasPtr
{
    friend void swap(HasPtr&,HasPtr&);
    friend void print(const HasPtr&);
public:
    HasPtr()=default;
    HasPtr(const string& s,int val):ps(new string(s)),i(val) {}
    HasPtr& operator=(const HasPtr&);
    bool operator<(const HasPtr& rhs);
    ~HasPtr() { delete ps; }
private:
    string* ps;
    int i;
};

HasPtr& HasPtr::operator=(const HasPtr& rhs)
{
    auto newp=new string(*(rhs.ps));
    delete ps;
    ps=newp;
    i=rhs.i;
    return *this;
}

bool HasPtr::operator<(const HasPtr& rhs)
{
    return (*(*this).ps<*rhs.ps);
}

void swap(HasPtr& lhs,HasPtr& rhs)
{
    using std::swap;
    swap(lhs.ps,rhs.ps);
    swap(lhs.i,rhs.i);
    cout<<"执行swap函数!"<<endl;
}

void print(const HasPtr& hp)
{
    cout<<*hp.ps<<" "<<hp.i<<endl;
}

int main()
{
    vector<HasPtr> vec;
    string s;
    int val;
    cout<<"输入一个字符串和整数:";
    while(cin>>s && cin>>val)
    {
        HasPtr hp(s,val);
        vec.push_back(hp);
        cout<<"继续输入吗? Y/N"<<endl<<"输入:";
        char ch;
        cin>>ch;
        if(ch=='y' || ch=='Y')
            cout<<"继续输入一个字符串和一个整数:";
        else
            break;
    }
    sort(vec.begin(),vec.end());
    for(auto c:vec)
    {
        print(c);
        cout<<endl;
    }

    return 0;
}

主要问题就是operator<函数问题,sort执行不了,怎么改? 谢谢了!
2 回复
#2
rjsp2014-04-12 19:14
函数后加个const试试
我用的是手机,没法试验
#3
忠犬八公2014-04-12 20:12
回复 2楼 rjsp
可以了,谢谢!能解释一下吗?
1