【发布时间】:2013-11-03 03:56:09
【问题描述】:
人.h
#ifndef PERSON_H_
#define PERSON_H_
/* Person.h */
class Person {
int age;
std::string name;
public:
Person(int, std::string);
std::string getName();
int getAge();
};
#endif /* PERSON_H_ */
person(int std::string) 函数声明使用 std::string 名称,但我没有将它包含在头文件中。因此,我希望编译器抱怨缺少符号。然而它编译并运行良好!为什么?
剩下的代码……
Person.cpp
#include <string>
#include "Person.h"
Person::Person(int age, std::string name)
{
this->name = name;
this->age = age;
}
std::string Person::getName()
{
return this->name;
}
int Person::getAge()
{
return this->age;
}
Main.cpp
#include <string>
#include "Person.h"
int main() {
printFunc();
Person chelsea_manning(5, std::string("Chelsea Manning"));
}
另外,我是 C++ 新手,所以如果您发现我的代码/OOP 有任何奇怪之处,请告诉我。
【问题讨论】:
-
包含就像复制粘贴。看看将这些标头按顺序复制粘贴到您的 cpp 中会做什么。
-
尝试从 main.cpp 和 person.cpp 中删除
#include <string>看看会发生什么;)。 -
尝试颠倒包含的顺序
-
阅读 C 和 C++ 中的“翻译单元”。
-
一般情况下,头文件应该写成自己编译。要对此进行测试,请编写一个只有 `#include "Person.h" 的简单 .cpp 文件并尝试编译它。
标签: c++