【发布时间】:2010-06-07 11:46:59
【问题描述】:
我知道我们将尽可能使用前向声明而不是包含来加快编译速度。
我有这样的课程Person。
#pragma once
#include <string>
class Person
{
public:
Person(std::string name, int age);
std::string GetName(void) const;
int GetAge(void) const;
private:
std::string _name;
int _age;
};
还有这样的课程Student
#pragma once
#include <string>
class Person;
class Student
{
public:
Student(std::string name, int age, int level = 0);
Student(const Person& person);
std::string GetName(void) const;
int GetAge(void) const;
int GetLevel(void) const;
private:
std::string _name;
int _age;
int _level;
};
在 Student.h 中,我有一个前向声明 class Person; 以在我的转换构造函数中使用 Person。美好的。但是我已经完成了#include <string> 以避免在代码中使用std::string 时出现编译错误。这里如何使用前向声明来避免编译错误?有可能吗?
谢谢。
【问题讨论】:
-
你理解错了。尽可能不要使用前向声明,而是包含相关的头文件。
-
我从一些类似的文章中得到了这个想法。 www-subatech.in2p3.fr/~photons/subatech/soft/carnac/…
-
不要相信你在网上看到的一切。
-
遗憾的是,我在很多网站上都找到了这个提示:eventhelix.com/realtimemantra/headerfileincludepatterns.htm
-
如果 Bjarne Stroustrup 告诉您做某事 - 这可能是个好主意。如果网上某个不知名的人告诉你,你至少应该有点怀疑。