【问题标题】:Enums and Functions枚举和函数
【发布时间】:2013-03-29 04:28:46
【问题描述】:

我的CDrawView 类中有这个枚举声明:

enum shape{line, rect, elli};

在我的另一个名为 Shapemaker 的类中,我有一个函数应该从 CDrawView 类中获取枚举并评估它们

  Shape* Shapemaker::shapeCreate(CDrawView::shape)
 {
  if(CDrawView::shape.line == 0)
    return new Line();

  else if(CDrawView::shape.rect == 1)
    return new Rect();

  else if (CDrawView::shape.ellip == 2)
    return new Ellip();
 }

我通过Shapemaker::shapeCreate(current_shape) 调用该函数,其中current_shape 只是enum shape 的一个实例。

  shape current_shape;

这给了我编译错误:

error C2653: 'CDrawView' : is not a class or namespace name
Shapemaker.h(7): 

我不完全确定这是否是使用枚举和函数甚至比较枚举的正确方法。

error C2061: syntax error : identifier 'shape'
'Shapemaker::shapeCreate' : function does not take 1 arguments

CDrawView.h

class CDrawView : public CScrollWindowImpl<CDrawView>
{
  public:

   CDrawView();
   enum shape{line, rect, elli};
       shape current_shape;
       //...
};

定义Shapemaker::shapeCreate() 的文件在顶部执行#include "CDrawView.h"

【问题讨论】:

  • 如果它抱怨它不是一个类,我们将不得不看到CDrawView
  • .ellip.elli 的拼写错误。但是你还没有遇到那个错误。
  • "CDrawView 类中的枚举" - 定义Shapemaker::shapeCreate 的文件是否包括CDrawView 的标头?如果CDrawView 在命名空间中,则需要在前面加上Shape* Shapemaker::shapeCreate(namespace1::[namespace2::...::]CDrawView::shape) 等。
  • 欢迎来到 Stack Overflow。请尽快阅读FAQ。正如您从 cmets 到问题和答案所看到的那样,困难在于您没有在问题中提供足够的信息让我们向您解释问题。您需要显示声明 enum shape 的更大上下文。我们不需要更多的代码,但我们确实需要更多的代码。请阅读如何提供 SSCCE (Short, Self-Contained, Correct Example)。

标签: c++ function enums


【解决方案1】:

使用CDrawView::line 代替CDrawView::shape.line

CDrawView::shape 仅用于需要类型的地方 - 例如用于声明变量。

A::shape var = A::line;

下面的代码也没有意义

Shape* Shapemaker::shapeCreate(CDrawView::shape)
{
    if(CDrawView::shape.line == 0)
        return new Line();

    else if(CDrawView::shape.rect == 1)
        return new Rect();

    else if (CDrawView::shape.ellip == 2)
        return new Ellip();
}

改成

Shape* Shapemaker::shapeCreate(CDrawView::shape s)
{
    if(s == CDrawView::line)
        return new Line();

    else if(s == CDrawView::rect)
        return new Rect();

    else if (s == CDrawView::ellip)
        return new Ellip();
}

或者甚至更好地将其更改为使用switch case

原代码有很多问题

  1. 您没有函数参数的变量名称 - 我已将其更改为变量名称 s
  2. CDrawView::line 是一个常数 - 它总是为 0。所以它总是返回 true。您的函数将始终返回 new Line()
  3. 其他 ifs 也在比较 2 个常量,并且如果曾经达到它们也会返回 true - 但它们不会。

【讨论】:

  • 非常感谢..你是唯一能够回答我的人
  • @user2221404 我现在已经用更多的东西更新了答案。
猜你喜欢
  • 2014-01-16
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多