【发布时间】:2016-01-16 08:11:33
【问题描述】:
在codeblocks中一点一点学习c++,遇到了这个错误。我已经尝试了几个小时并看到了各种链接,但它仍然无法正常工作,
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
foo:: Person p;
//std:: cin >> p;
std:: cout << p;
return 0;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
namespace foo{
class Person
{
public:
int age;
Person();
friend std:: ostream& operator << (std::ostream&,const Person&);
//friend std:: istream& operator << (std:: istream& in, Person& p);
protected:
private:
// std::string name;
};
}
#endif // PERSON_H
Person.cpp
#include <iostream>
#include "Person.h"
using namespace foo;
Person::Person()
{
age = 0;
//name = "noname";
}
std:: ostream& operator <<(std:: ostream& out, Person const &p)
{
out << "Extraction operator" << std:: endl << p.age << std:: endl;
// out << p.name << std::endl;
return out;
}
/*std:: istream& operator >>(std:: istream& in, Person &p)
{
in >> p.age >> p.name;
return in;
}*/
第一季度。为什么我们需要在单独的命名空间中创建头文件和 Person.cpp? 猜猜:是不是因为 cout 只是表示全局命名空间,然后我们又遇到了一个重载的 cout,所以编译器不确定会调用哪个定义?
第二季度。通过在 main 的 foo 命名空间中创建 Person 类的对象 p 并调用 std::cout
错误:
undefined reference to foo:: operator<<(std::ostream&, foo::Person const&)')
如果我们私下写年龄,它表示它是私人的,但作为朋友,它应该可以访问私人成员。我知道这与命名空间有关,但我找不到原因。
no match for operator >> in std::cin 早些时候它给出了上述和许多其他错误,所以我尝试使用两个命名空间,但仍然无法正常工作。
【问题讨论】:
-
每个问题一个问题。
标签: c++ namespaces operator-overloading