【问题标题】:error: argument of type ‘char (CharStack::)()const throw (CharStack::Underflow)’ does not match ‘char’错误:“char (CharStack::)()const throw (CharStack::Underflow)”类型的参数与“char”不匹配
【发布时间】:2012-03-08 20:24:20
【问题描述】:

问题的标题是错误本身,但我也将其包括在下面:

error: argument of type ‘char (CharStack::)()const throw (CharStack::Underflow)’ does not match ‘char’

这是我正在使用的代码文件:

#include <iostream>
#include "CharStack.h"
using namespace std;

// returns top value on stack
// throws exception if empty
//
// O(n)
char CharStack::top() const throw( Underflow )
{
    Elem * cur = head;

    if( !empty() )
    {
        while( cur && cur -> next )
            cur = cur -> next;

        return cur -> info;
    }
}


int main()
{
    CharStack * stack = new CharStack();

    char top = stack -> top;

    stack -> push( 't' );
    stack -> push( 'e' );
    stack -> push( 's' );
    stack -> push( 't' );
    stack -> push( 'i' );
    stack -> push( 'n' );
    stack -> push( 'g' );

    stack -> output( cout );

    delete stack;
}

在头文件中,我定义了我使用的两个异常,作为我下面的示例:

     public:
     // exceptions
        class Overflow{};
        class Underflow{};

我认为这是因为我没有处理摘录,但在目前的情况下我不知道如何处理它。

谢谢

【问题讨论】:

    标签: c++ exception-handling compile-time


    【解决方案1】:
    return cur -> info;
    

    info 是返回 char 的成员函数吗?那么你应该使用:

    return cur -> info();
    

    否则你将返回一个指向成员函数的指针,而不是一个字符。

    同样的:

    char top = stack -> top;
    

    stack-&gt;top是成员函数指针,stack-&gt;top()是对stack对象的top函数的调用。

    顺便说一句,如果empty() 为真,您的top 函数不会返回任何内容,这是非法的。您需要返回 char 或抛出,但不返回或抛出而离开函数是不正确的。

    【讨论】:

    • 对不起,“Elem”是一个有两个变量的结构:Elem * next;和字符信息;所以 Elem -> info 只是获取存储在结构中的字符。我应该更清楚。
    • 关于stack-&gt;top 是成员函数的部分仍然有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 2016-05-19
    • 2020-01-20
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2014-07-03
    相关资源
    最近更新 更多