C ++:将方法转换为另一种方法

时间:2020-10-15 16:46:33

标签: c++

我是C ++的新手,所以请不要对我苛刻。

这是我的标题cblock.hpp

#ifndef CBLOCK_H
#define CBLOCK_H
#include "ctime.hpp"
#include <iostream>

class CBlock
{
 public:
   CBlock();
   CBlock(short m_BlockNr,CTime m_Begin);

   short getBlockNr();
   void print() const;
   void getEnd();
   
   ~CBlock(){};

 private:
   short BlockNr = 1;
   CTime Begin;


};

#endif

这是cblock.cpp

#include "cblock.hpp"
#include <iomanip>

using namespace std;

CBlock::CBlock(short m_BlockNr, CTime m_Begin)
{
  BlockNr = m_BlockNr;
  Begin = m_Begin;
}

short CBlock::getBlockNr()
{
  return BlockNr;
}

void CBlock::getEnd() //Adding 90 Minutes to the current time
{
  int STD = (Begin.Minute + 30) / 60;
  Begin.Minute = (Begin.Minute + 30) % 60;
  Begin.Hour = Begin.Hour + 1 + STD;
}

void CBlock::print() const
{
  //Current time
  cout << setfill('0') << setw(2) << Begin.Hour << ":" << setw(2) << Begin.Minute << " – "; 
 
  getEnd();  //I know this is not possible but I guess you understood what I'm trying to do here.

  //After 90 Minutes 
  cout << setfill('0') << setw(2) << Begin.Hour << ":" << setw(2) << Begin.Minute << endl; 
 
}

我希望getEnd()方法更改Begin.HourBegin.Minute,但是我不知道如何在另一个方法中调用一个方法。

1 个答案:

答案 0 :(得分:0)

当然有可能!

麻烦之处在于您的print()函数是const,这意味着它只能以const的方式访问其类。

getEnd()不是 const,因此print()无法调用它。

实际上叫“ get”设置设置有点奇怪;也许您想从该函数返回一个新值?您可以将其称为calculateEnd()。您以后可以随时分配它。

但是,如果您确实希望print()中的这些操作来修改其类,则无法将其标记为const,因为const意味着它无法修改其类。