如何向类添加属性
How to add a property to a class
我正在开发一个新的应用程序,基于模板、STL、命名空间......(我的同事已经采取了所有必要的步骤来弄得一团糟),现在我只想向类添加一个属性,这不起作用,让我向您展示):
在头文件中:
namespace utils{
class Logging_Manager : public Singleton<Logging_Manager> {
friend Singleton<Logging_Manager>;
Logging_Manager();
private:
std::vector<std::shared_ptr<Single_Logger>> logging_modules;
LogLevelType loglevel; // 0 : no logging, 1 : info logging, (2-4 are not used), 5 : debug, 6 : everything
public:
Timer getDebuggerTimer;
Timer getFileTimer;
我刚刚添加了最后一个条目getDebuggerTimer
并getFileTimer
自己,由于编译器错误 C3646 和 C4430,这无法编译。
我的意思是两者都是Timer
类型的属性,我并不是说这些东西是某些方法的模板,这些方法可能是抽象的、虚拟的或其他任何东西,不,它们只是作为属性,仅此而已。
由于我没有找到将两个计时器添加到我的头文件的方法,我的老板刚刚解决了这个问题,如下所示:
class Timer; // this class is defined elsewhere, how can it be put here and make things work?
namespace utils{
class Logging_Manager : public Singleton<Logging_Manager> {
friend Singleton<Logging_Manager>;
Logging_Manager();
private:
std::shared_ptr<Timer> getDebuggerTimer;
std::shared_ptr<Timer> getFileTimer;
换句话说:他没有添加包含,但他添加了对标题不知道的内容的引用:class Timer
.
最重要的是,他添加了一个共享指针,它神奇地做了一些事情。
我在这里完全迷失了:看起来 STL 添加了编程规则,例如:- 如果你想让某些东西工作,
不要添加包含,而是添加一个引用(但你的代码如何知道引用的含义? - 您可以添加共享指针(或其他 STL 发明),这些指针将使您的代码正常工作。
?????
谁能对此有所了解?
如果要将Timer
聚合到类定义中,编译器需要知道Timer
是什么。因此,您可以使用#include "Timer.h"
(使用正确的标题)。
你的老板做了什么,是双重
的- 使用指针而不是成员对象。从而允许它工作 使用前向声明而不是包含。
- 使用智能 指针而不是原始指针。这是很好的做法。
这与模板和 STL 无关。
你应该看看什么是前向声明:
你的老板对此做了什么
class Timer;
是对编译器说"嘿,看,有一种叫做 Timer 的东西,你还不知道,相信我并为它预留一些空间"。
编译器回答正常,但它必须知道为构造该对象分配多少空间。由于您使用对象并且不包含包含它的头文件,因此编译器不知道它占用多少空间并给出错误。如果使用指针(或智能指针),编译器确实只需要为指针保留空间,并且可以执行此操作。当然,如果要在实现中使用它,则必须包含时间标头。
出于同样的原因,您不能转发声明要继承的类。
计时器.h
class Timer
{
public:
void time() { std::cout << "time!"; }
}
你的班级.h
class Timer; // forward declaration
class Manager
{
public:
void doStuff() {}
private:
Timer* t1; // this will work
std::shared_pointer<Timer> t2; // this will work
//Timer t3; // this one don't
}
}
这种情况不起作用:
class Timer;
class SpecialTimer : public Timer
{
// ... do stuff
}
关于前向声明的一些链接:
https://en.wikipedia.org/wiki/Forward_declaration
这篇文章有一个很好的解释。
- 如何在Qt C++中向自定义控件添加属性?
- OpenGL - 添加第二个着色器属性会导致空白屏幕
- 递归添加子树以提升属性树
- 将具有 xml 属性的子树添加到提升属性树
- 我创建了deque<CObject*>并添加了不同类型的元素。如何更改此元素的属性?
- 如何向类添加属性
- 如何将按钮添加到节点的属性编辑器面板,该面板调用该节点内的方法?
- 如何在Boost Graph库中的Grid_graph的边缘添加自定义属性
- 如何使用属性包添加边缘以提升::adjacency_matrix
- 如何在虚幻引擎4中将属性添加到变换类别
- 为什么Clang自动将属性添加到我的功能中
- cmake 如何在项目的 vcxproj 属性组中添加自定义条目?
- Clang在发出LLVM IR时向所有函数添加noinline属性
- 将属性添加到QT C 中的Qpushbutton
- 向向下转换结构添加属性值会导致分段错误
- QTreeWidgterItem-隐藏值或添加属性
- 如何使用xerces向xml添加属性
- 如何向lambda函数添加属性
- 为什么c++ 17向名称空间和枚举数添加属性?
- 如何在c++中为已有的IXMLDOMNode添加属性