我一直在試圖去'pimpl'的習語中,但是我無法得到想要編譯的東西。編譯一個pimpl習語代碼的問題
在Linux Mint的使用g ++ 4.6.3 v我得到以下錯誤:
$ g++ main.cc
/tmp/ccXQ9X9O.o: In function `main':
main.cc:(.text+0xd7): undefined reference to `Person::Person(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)'
collect2: ld returned 1 exit status
這是我的代碼:
person.hh
#ifndef PERSON_HH
#define PERSON_HH
#include <tr1/memory>
#include <string>
class Person
{
private:
class PersonImpl;
std::tr1::shared_ptr<PersonImpl> pImpl;
public:
Person(const std::string& name, int age=0);
~Person();
const std::string& get_name() const;
int get_age() const;
};
#endif
person.cc
#include <string>
#include "person.hh"
class Person::PersonImpl
{
public:
std::string name;
int age;
PersonImpl(const std::string& n, int a) : name(n), age(a) {}
};
Person::Person(const std::string& name, int age) : pImpl(new PersonImpl(name, age)) {}
Person::~Person() {}
const std::string& Person::get_name() const { return pImpl->name; }
int Person::get_age() const { return pImpl->age; }
main.cc
#include <iostream>
#include "person.hh"
int main()
{
const std::string name = "foo";
Person p(name, 50);
return 0;
}
除了代碼錯誤,你能不能請告知方法,我已經採取了模仿「平普爾」成語?這符合它嗎?
感謝unique_ptr建議和這個特殊情況下的初始化列表,我在解決鏈接問題時發現了一些其他的問題。 – Nobilis
@Nobilis:很高興幫助:) –