HasPtr.h
#ifndef HASPTR_H
#define HASPTR_H
#include <string>
class HasPtr {
friend inline void swap(HasPtr&, HasPtr&);
public:
HasPtr(const std::string &s = std::string()):
ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &p):
ps(new std::string(*p.ps)), i(p.i) {}
HasPtr& operator=(const HasPtr &hp);
~HasPtr() { delete ps; }
private:
std::string *ps;
int i;
};
#endif
HasPtr.cpp
#include <utility>
#include <iostream>
#include "HasPtr.h"
HasPtr& HasPtr::operator=(const HasPtr &hp)
{
*ps = *hp.ps;
i = hp.i;
return *this;
}
inline
void swap(HasPtr &l, HasPtr &r)
{
using std::swap;
swap(l.ps, r.ps);
swap(l.i, r.i);
std::cout<<"Hello World"<<std::endl;
}
main.cpp
#include <iostream>
#include "HasPtr.h"
int main()
{
HasPtr a("a"), b("b");
swap(a, b);
return 0;
}
为什么执行:
g++ main.cpp HasPtr.cpp
会报如下错误:
in function `main':
undefined reference to `swap(HasPtr&, HasPtr&)'
为什么 main
中调用不了 swap
?
inline 函数定义放在头文件。
https://blog.csdn.net/tonywea...