什么功能这个类? [英] Whats function of this class?

查看:71
本文介绍了什么功能这个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读模板上的一些教程时,我偶然发现了一个类,后来在声明模板类对象时用作float,但是无法理解为什么需要它,如果有人可以解释

While reading some tutorial on template, i stumbled upon a class which was used as a float later while declaring template class object, but couldn't understand why its needed, if any one could explain

class Number {
  float f;
public:
  Number(float ff = 0.0f) : f(ff) {}
  Number& operator=(const Number& n) {
    f = n.f;
    return *this;
  }
  operator float() const { return f; }
  friend ostream&
    operator<<(ostream& os, const Number& x) {
      return os << x.f;
  }
};

推荐答案

这个片段来自这里(最后一个例子):http://www.fi.muni.cz/usr/jkucera/tic/tic0169.html [ ^ ],问题证明了将代码脱离上下文的问题。



Eckel谈论使用内置类型作为模板参数。在我看来,这个例子没有完全解释。



他本可写的:

This snippet comes from here (the last example): http://www.fi.muni.cz/usr/jkucera/tic/tic0169.html[^] and the question demonstrates the problem with taking code out of context.

Eckel is talking about using built in types as template arguments. In my opinion the example is not explained fully.

He could have written:
Holder<float,> h;



并获得相同的输出。但是使用float的包装类,Number允许在构造函数中初始化值。



这样做:


and got the same output. However the use of the wrapper class for float, Number allows initialization of the value in the constructor.

Doing this:

int main() {
  Holder<number,> h;
  for(int j = 0; j < 20; j++)
    cout << h[j] << endl;
} ///:~ 





我们看到Number的构造函数中的值设置为0.



如果我们这样做:



we see that the the values are set to 0 in the constructor of Number.

If we do this:

int main() {
  Holder<float,> h;
  for(int j = 0; j < 20; j++)
    cout << h[j] << endl;
} ///:~ 





然后我们有未初始化的值。



then we have uninitialized values.


该类实际上在一个对象中包装了一个 float 。我没有看到为什么需要它的原因(但是我也没有看到任何使用它的代码)。
The class actually wraps a float in a object. I don't see any reason why it is needed, however (I don't see any code using it as well, however).


float是一种所谓的值类型。它们只是主要值,没有任何实例甚至类方法或属性。值类型没有备份它们的类。当需要模板< class T> 时,您将无法直接使用float或int。但是当封装在类似数字的类中时,你可以。您现在拥有引用类型而不仅仅是值类型。这个Number类就像Java中的装箱/拆箱一样。



祝你好运!
A float is a so called value type. They are just primary values and don't have any instance or even class methods or properties. Value types don't have a class backing them up. When a template<class T> is required, you wouldn't be able to use float or int directly. But when encapsulated in a class like number you can. You now have a reference type instead of just a value type. This Number class is like boxing/unboxing in Java.

Good luck!


这篇关于什么功能这个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆