C++调用不了内联函数?

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

阅读 2.6k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题