【问题标题】:int_type not naming type frustrationint_type 不命名类型挫折
【发布时间】:2016-12-05 21:45:49
【问题描述】:

我在code being adapted from here 中有一个虚拟方法类型int_type,这是代码给出编译错误的唯一情况:

‘int_type’ does not name a type
 int_type ThreadLogStream::overflow(int_type v)
 ^.

到目前为止的调试步骤

    1234563
  • 根据this reference,int_type确实属于basic_streambuf,但称它为Traits::int_type不起作用。

  • 我尝试对问题变量进行 typedef,如下面的 typedef 所示,但无法识别 char_typetraits_type

threadlogstream.cpp

...
int_type ThreadLogStream::overflow(int_type a)
{
    int_type b = a; //This gives no errors

    return b;
}
...

threadlogstream.hpp

#include <iostream>
#include <streambuf>
#include <string>

//typedef std::basic_streambuf< char_type, traits_type> base_class;
//typedef typename base_class::int_type int_type;

class ThreadLogStream :  public QObject, std::basic_streambuf<char> {

    Q_OBJECT

public:
    ThreadLogStream(std::ostream &stream);
    ~ThreadLogStream();

protected:
    virtual int_type overflow(int_type v); // This gives no errors
    virtual std::streamsize xsputn(const char *p, std::streamsize n);
}

请帮忙 - 我正在为此脱发。

【问题讨论】:

  • 如果在全局命名空间中没有看到int_type,则不应该编译。当函数在类之外声明时,您应该使用限定名称作为返回类型。

标签: c++ std typedef virtual-functions streambuf


【解决方案1】:

您的int_type 似乎应该代表std::basic_streambuf&lt;&gt;::int_type。在这种情况下,您应该在 out-of-class 成员定义中编写

ThreadLogStream::int_type ThreadLogStream::overflow(int_type a)
{
  ...

即为函数返回类型使用限定名称。在类范围内查找参数名称(这就是为什么在参数列表中仅使用 int_type 可以很好地编译的原因)。但是返回类型是在封闭范围内查找的,这就是为什么你必须明确地对其进行质量。

在 C++ 中一直如此。

但是,尾随返回类型语法中的返回类型(自 C++11 起可用)也在类范围内查找,这意味着您可以选择这样做

auto ThreadLogStream::overflow(int_type a) -> int_type
{
  ...

【讨论】:

    【解决方案2】:

    看起来您需要将其设为尾随返回类型,如下所示:

    auto ThreadLogStream::overflow(int_type v) -> int_type {
        // ...
    }
    

    解释:int_type 需要在 ThreadLogStream 的范围内查找,但如果您有一个前导返回类型,它将在命名空间范围内查找,因为它在您之前提及名称ThreadLogStream::overflow,它会触发ThreadLogStream 范围内的查找。通过将返回类型放在 qualified-id 之后,可以避免这个问题。

    【讨论】:

    • 前面不应该有auto吗?
    • @Pixelchemist 是的,对不起,我修好了
    猜你喜欢
    • 2018-01-21
    • 2011-02-24
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 2020-09-19
    相关资源
    最近更新 更多