【问题标题】:'.' cannot appear in a constant-expression'。'不能出现在常量表达式中
【发布时间】:2017-11-02 11:37:34
【问题描述】:
template <class T>
struct stkNode
{
    BinTreeNode<T> *ptr;
    enum tag {R,L}tag;
    stkNode(BinTreeNode<T> *N = NULL) : ptr(N),tag(L){}
};

template<class T>
void BinaryTree<T>::PostOrder(void(*visit)(BinTreeNode<T> *p))
{
    SeqStack<stkNode<T> > S;
    stkNode<T> w;
    BinTreeNode<T> *p = root;
    do
    {
        while (p != NULL)
        {
            w.ptr = p;
            w.tag = w.L;
            S.Push(w);
            p = p->leftChild;
        }

        bool continuel = true;
        while (!S.IsEmpty() && continuel)
        {
            S.Pop(w); 
            p = w.ptr;

            switch (w.tag)
            {
            case w.L: //---------------this line--------------------------
                w.tag = w.R;
                S.Push(w);
                continuel = false;
                p = p->rightChild;
                break;
            case w.R: // -----------and this line-------------
                visit(p);
                break;
            }
        }
    } while (!S.IsEmpty());
}

当我在 Devc++ 上编译它时,会出现如下错误: [错误] '。'不能出现在常量表达式中。 但是当我在 Visual Studio 2015 上编译它时,不会发生错误。 为什么??????

-----------更新我的问题-------- 比如

    #include <iostream>
using namespace std;

struct exp
{
    char ch;
    enum dir{
        L,R
    }direction;
    exp(char name,dir d){
        ch = name;
        direction = d;
    }
};
int main()
{
    exp t('a',exp.L); //this line
    return 0;
}

是一样的

【问题讨论】:

  • 这段代码不完整,根本无法编译。请创建一个minimal reproducible example
  • 好的,我已经更新了。
  • 第二个例子不同,可以通过使用范围运算符exp::L来修复。在第一种情况下,点左侧有一个变量,在第二种情况下,它是一个类型。
  • 你的枚举访问方式不对

标签: c++ c++11 visual-c++


【解决方案1】:

问题是我错误地访问了枚举的方法...... 正确的代码是:

template<class T>
void BinaryTree<T>::PostOrder(void(*visit)(BinTreeNode<T> *p))
{
    SeqStack<stkNode<T> > S;
    stkNode<T> w;
    BinTreeNode<T> *p = root;
    do
    {
        while (p != NULL)
        {
            w.ptr = p;
            w.tag = w.L;
            S.Push(w);
            p = p->leftChild;
        }

        bool continuel = true;
        while (!S.IsEmpty() && continuel)
        {
            S.Pop(w); 
            p = w.ptr;
            switch (w.Tag)
            {
            case stkNode<T>::L:
                w.tag = w.R;
                S.Push(w);
                continuel = false;
                p = p->rightChild;
                break;
            case stkNode<T>::R:
                visit(p);
                break;
            }
        }
    } while (!S.IsEmpty());
}

【讨论】:

  • 侧节点:您用c++11 标签标记了您的问题,您的代码中有一些非C++ 11。例如:旧式函数指针(而不是 std::function&lt;void(BinTreeNode&lt;T&gt; *)&gt;)和 NULL 而不是 nullptr
  • 您标记了 C++11,因此您可以使用 decltype():而不是 case stkNode&lt;T&gt;::L:,您可以使用 case decltype(w)::L。这是同一件事,但(恕我直言)在某些情况下,可以更清楚地阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多