简体   繁体   English

C ++ / Qt QTime - 如何使用该对象

[英]C++ / Qt QTime - How to use the object

this is more a generell C++ beginner Question: 这更像是一个基本的C ++初学者问题:

I have 2 classes: 我有2个班:

  • Class A, including a 'ReadData' Method, which is called as soon as new Data is received by a TCP Socket A类,包括'ReadData'方法,一旦TCP Socket接收到新数据就会调用它
  • Class B, including a Method 'Start' which is sending big amounts of data via TCP. B类,包括通过TCP发送大量数据的方法“开始”。

Due to the architecture, its not possible to have both methods in one class. 由于该体系结构,它不可能在一个类中同时具有这两种方法。

What I want to do: 我想做的事:

  1. Start a Timer as soon as 'Start' in Class B is invoked. 一旦调用B类中的“开始”,就立即启动计时器。
  2. Stopp the Timer as soon as the 'ReadData'in Class A is invoked. 一旦调用A类中的'ReadData',就立即停止计时器。
  3. Then i will calc the difference to see how long it took... 然后我会计算差异,看看花了多长时间......

My Question: 我的问题:

  • Where do I create the Object: 我在哪里创建对象:

     QTimer transferTimer; 
  • How can I pass the Object to my both Classes? 如何将Object传递给我的两个类?

How is the proper way in C++ to handle this? 如何在C ++中正确处理这个问题?

Thank you. 谢谢。

Here is one of the possible solutions. 这是可能的解决方案之一。 It's simplified to demonstrate the idea: 它简化了以展示这个想法:

class C
{
public:
  void start()
  {
    m_startTime = QTime::currentTime();
  }

  void stop()
  {
    m_endTime = QTime::currentTime();
  }

  int difference() const
  {
    return m_startTime.secsTo(m_endTime);
  }

private:
  QTime m_startTime;
  QTime m_endTime;
};

class A
{
public:
  A(std::shared_ptr<C> c) : m_c(c)
  {}

  void ReadData()
  {
    // ...
    m_c->stop();

    int transferTime = m_c->difference(); // seconds
  }

private:
  std::shared_ptr<C> m_c;
};

class B
{
public:
  B(std::shared_ptr<C> c) : m_c(c)
  {}

  void start()
  {
    // ...
    m_c->start();
  }

private:
  std::shared_ptr<C> m_c;
};

int main(int argc, char ** argv)
{
  auto c = std::make_shared<C>();
  // a and b keep reference to instance of class C
  A a(c);
  B b(c);

  [..]
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM