ReadingLab/Discussion-for-Cpp

《C++ Primer》 7.1-7.2部分

Lantry28 opened this issue · 1 comments

Person.h:
#include
#include
using namespace::std;

class Person{
public:
Person() = default;
Person(const string &s, const string &r) :
names(s), adds(r){
}
Person(istream& is){
read(is, *this);
}
string names;
string adds;

const string& getName() const{ return names; };
const string& getAdds() const{ return adds; };

friend istream& read(istream& is, Person& person);
friend ostream& print(const ostream& os, const Person& person);

};

istream& read(istream &is, Person& person){
is >> person.names >> person.adds;
if (!is)
person = Person(); //奇怪的if
return is;
}

ostream& print(ostream &os, const Person& person){
os << person.names << " " << person.adds << endl;
return os;
}

test:
#include "Person.h"
int main(){
Person mine;
print(cout, mine) << endl;
system("pause");
return 0;
}

error LNK2005: "class std::basic_ostream<char,struct std::char_traits > & __cdecl print(class std::basic_ostream<char,struct std::char_traits > &,class Person const &)" (?print@@yaaav?$basic_ostream@DU?$char_traits@D@std@@@std@@aav12@ABVPerson@@@z) 已经在 Person.obj 中定义 D:\C++Test\Project7\Project7\test.obj Project7

error LNK2005: "class std::basic_istream<char,struct std::char_traits > & __cdecl read(class std::basic_istream<char,struct std::char_traits > &,class Person &)" (?read@@yaaav?$basic_istream@DU?$char_traits@D@std@@@std@@aav12@AAVPerson@@@z) 已经在 Person.obj 中定义 D:\C++Test\Project7\Project7\test.obj Project7

error LNK1169: 找到一个或多个多重定义的符号 D:\C++Test\Project7\Debug\Project7.exe Project7

建议:

  • 标题明确一下提出的问题.
  • 内容给出详细的描述包括但不限于 现象&报错&尝试&疑问
  • 贴关键代码无关代码不要贴, 注意下格式.

方便别人查阅&回答&学习.