这是书上题目:
为你的HasPtr类定义一个<运算符,并定义一个HasPtr的vector,为这个vector添加一些元素,并对它执行sort。注意何时会调用swap。
然后这是我写的代码:
head.h
#include <iostream>
#include <string>
class HasPtr
{
friend void swap(HasPtr& lhs, HasPtr& rhs);
public:
HasPtr(const std::string& s = std::string());
HasPtr(const HasPtr& obj);
HasPtr& operator=(HasPtr& obj);
HasPtr& operator=(const std::string &rhs);
bool operator<(HasPtr& obj);
void print();
~HasPtr();
private:
std::string* ps;
int i;
};
inline void swap(HasPtr& lhs, HasPtr& rhs);
HasPtr.cpp
```c++
#include "head.h"
using namespace std;
HasPtr::HasPtr(const string& s) :ps(new string(s)), i(s.size())
{
}
HasPtr::HasPtr(const HasPtr& obj) : ps(obj.ps), i(obj.i)
{
}
HasPtr& HasPtr::operator=(HasPtr& obj)
{
ps = obj.ps;
i = obj.i;
return *this;
}
bool HasPtr::operator<(HasPtr& obj)
{
return *ps < *obj.ps;
}
void HasPtr::print()
{
cout << *ps << ' ' << i << endl;
}
HasPtr::~HasPtr()
{
}
HasPtr& HasPtr::operator=(const string& rhs)
{
*ps = rhs;
return *this;
}
main.cpp
#include "head.h"
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<HasPtr> list;
list.emplace_back("one");
list.emplace_back("two");
list.emplace_back("three");
sort(list.begin(), list.end());
for (HasPtr i : list)
i.print();
return 0;
}
void swap(HasPtr& lhs, HasPtr& rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
cout << "交换成功!" << endl;
}
编译后报错,内容为:
我的问题就是我已经定义了<操作符,且主程序如果写上u1<u2但会的也是0,为什么还会报错?