如何向类添加属性

How to add a property to a class

本文关键字:添加 属性      更新时间:2023-10-16

我正在开发一个新的应用程序,基于模板、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;

我刚刚添加了最后一个条目getDebuggerTimergetFileTimer自己,由于编译器错误 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"(使用正确的标题)。

你的老板做了什么,是双重

  1. 使用指针而不是成员对象。从而允许它工作 使用前向声明而不是包含。
  2. 使用智能 指针而不是原始指针。这是很好的做法。

这与模板和 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

这篇文章有一个很好的解释。