【问题标题】:converting structure to class将结构转换为类
【发布时间】:2017-09-27 16:22:03
【问题描述】:

我正在尝试将结构转换为类,但我不完全确定类头文件中的具体内容。我做了一些改变,谁能告诉我还有什么需要改变的?谢谢!

结构:

enter code here: 
#ifndef TIME_H
#define TIME_H

#include <iostream>

struct Time {
int hours, minutes, seconds;
};

void init(Time &t, int hours, int minutes, int seconds);
void normalize(Time &t);
Time operator +(const Time &t1, const Time &t2);
Time &operator +=(Time &t1, const Time &t2);
Time operator -(const Time &t1, const Time &t2);
Time &operator -=(Time &t1, const Time &t2);
bool operator ==(const Time &t1, const Time &t2);

std::ostream &operator <<(std::ostream &os, const Time &t);
std::istream &operator >>(std::istream &is, Time &t);

#endif

类:

#define TIME_H

#include <iostream>

class Time {


public:
void init(Time &t, int hours, int minutes, int seconds);
void normalize(Time &t);
Time operator +(const Time &t1, const Time &t2);
Time &operator +=(Time &t1,const Time &t2);
Time operator -(const Time &t1, const Time &t2);
Time &operator -=(Time &t1, const Time &t2);
bool operator ==(const Time &t1, const Time &t2);
std::ostream &operator <<(std::ostream &os, const Time &t);
std::istream &operator >>(std::istream &is, Time &t);
private: 
int hours, minutes, seconds;

};

#endif

【问题讨论】:

  • 在 C++ 中,struct 与 class 相同,唯一不同的是 - 默认情况下,struct 中是 public,而 class 中是 private
  • real 代码是否工作?如果是这样,这个问题可能不属于这里,应该在code review
  • 你应该将init重命名为Time(它的构造函数),在某些情况下你需要添加~Time()(析构函数)
  • @WhozCraig 阅读codereview.meta.stackexchange.com/questions/5777/…,看看你是否认为这个问题真的符合他们的标准。

标签: c++ class header structure


【解决方案1】:

您应该始终使用构造函数和析构函数而不是“init”或“close”方法:Time(int hrs, int secs, int mins)。还提供一个默认构造函数,将成员初始化为一些默认值。 考虑将它们定义为 unisgned int,因为它们不能变为负数。 此外,如果您只想访问流接口,请包含 &lt;iosfwd&gt; 而不是 &lt;iostream&gt;

【讨论】:

  • 所以它会是: void Time(int hours, int minutes, int seconds);
  • 谢谢,我还有什么需要改变的吗?
猜你喜欢
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2016-09-10
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2012-11-12
相关资源
最近更新 更多