【问题标题】:Why this c++ function is a struct为什么这个 c++ 函数是一个结构体
【发布时间】:2014-08-17 15:07:04
【问题描述】:

我正在学习 C++,对使用 Trust Library 的 C++ 代码有点困惑。以下是我的问题:

  1. 为什么要使用关键字struct
  2. 为什么函数is_word_start有冒号部分::public push::binary_function"

    // determines whether the right character begins a new word
    struct is_word_start
        : public thrust::binary_function<const char&, const char&, bool>
    {
        __host__ __device__
        bool operator()(const char& left, const char& right) const
        {
            return is_alpha(right) && !is_alpha(left);
        }
    };
    

https://github.com/thrust/thrust/blob/master/examples/word_count.cu

【问题讨论】:

  • 函数执行operator()可以在这个类的实例上调用,因此可以作为简单函数调用的替代调用。
  • 请继续学习C++。此时您可能还没有为 Stack Overflow 做好准备。
  • is_word_startclass,而不是函数。
  • 冒号部分表示继承。此外 is_word_start 不是一个函数,而是一个function object 类。

标签: c++


【解决方案1】:
  1. struct 的含义与 class 的含义几乎相同,只是默认情况下 struct 的所有成员都是公共的,而在类中它们是私有的。 (您可以像在类中一样在结构中指定访问修饰符。)
  2. : public 部分表示公共继承。您应该认真阅读这种和其他继承类型。

这个类重载了一个所谓的调用操作符,因此这个类的一个对象可以作为一个函数被调用(在这个特殊的情况下有两个参数)。这样的对象通常被称为函子,广泛用于 stl 和其他任何地方。

【讨论】:

  • 另外,public 不是必需的,因为默认情况下struct 的基类是public(您在第 1 点中忽略了这一点)。
猜你喜欢
  • 2019-01-16
  • 1970-01-01
  • 2021-11-08
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多