【发布时间】:2020-05-07 17:01:46
【问题描述】:
我想创建一个类 Student,它有一个类型库 std::string 的成员,但我不想在我的 Student.h 中包含标题 <string> 并且只使用前向声明:
// Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
typedef class string_ string;
struct Student
{
public:
Student(const string_&, std::size_t);
const string_ name()const;
void setName(const string_&);
std::size_t age()const;
void setAge(std::size_t);
private:
string_* name_ ;
std::size_t age_;
};
// Student.cpp
#include "Student.h"
#include <string>
Student::Student(const std::string& str, std::size_t a) :
name_(&str),
age_(a)
{}
编译程序时出现以下错误:
../src/Student.cpp:13:2: error: no declaration matches ‘Student::Student(const string&, std::size_t)’ 13 | Student::Student(const std::string& str, std::size_t a) :那么我是否可以使用前向声明,以便在标头中不包含任何标头,而只是前向声明我需要的类型,然后在源中包含标头?
-
我这样做是因为我正在阅读 Guillaume Lazar 的 Mastering Qt5 一书,他在其中给出了这个例子:
//SysInfoWindowsImpl.h #include <QtGlobal> #include <QVector> #include "SysInfo.h" typedef struct _FILETIME FILETIME; class SysInfoWindowsImpl : public SysInfo { public: SysInfoWindowsImpl(); void init() override; double cpuLoadAverage() override; double memoryUsed() override; private: QVector<qulonglong> cpuRawData(); qulonglong convertFileTime(const FILETIME& filetime) const; private: QVector<qulonglong> mCpuLoadLastValues; }; //SysInfoWindowsImpl.cpp #include "SysInfoWindowsImpl.h" #include <windows.h> SysInfoWindowsImpl::SysInfoWindowsImpl() : SysInfo(), mCpuLoadLastValues() { } void SysInfoWindowsImpl::init() { mCpuLoadLastValues = cpuRawData(); } qulonglong SysInfoWindowsImpl::convertFileTime(const FILETIME& filetime) const { ULARGE_INTEGER largeInteger; largeInteger.LowPart = filetime.dwLowDateTime; largeInteger.HighPart = filetime.dwHighDateTime; return largeInteger.QuadPart; }
"语法typedef struct _FILETIME FILETIME是一种转发
FILENAME 语法的声明。由于我们只使用参考,我们可以避免
在我们的文件 SysInfoWindowsImpl.h 中包含标签并保留它
在 CPP 文件中。”来自书中。
- 那么有人可以向我解释他如何使用在
windows.h中定义的typedef struct _FILETIME吗?谢谢。
【问题讨论】:
-
typedef class string_ string;- 这不是前向声明。而且我会回避这样的别名。他们会在某个时候咬你。 -
@JesperJuhl:我在 Qt 书中看到过这样的例子:
typedef struct _FILETIME FILETIME;你觉得怎么样? -
我想我不知道你在问什么。你明白那行代码是做什么的吗?您是在问为什么这在 Qt 中有意义吗?您是否只是复制'n'粘贴您在其他地方看到的东西,希望它能解决您的问题,但没有真正理解它(我目前的猜测)?