C++ 错误:非静态成员引用必须相对于特定对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15691115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:39:50  来源:igfitidea点击:

error:a nonstatic member reference must be relative to a specific object

c++staticenums

提问by user1665569

I don't understand why view gives me the error of a nonstatic member reference must be relative to a specific object.

我不明白为什么视图给我非静态成员引用必须与特定对象相关的错误。

CDrawView::Shapeis an enum that i have declared on my CDrawView

CDrawView::Shape是我在我的 CDrawView

enum shape{line, rect, elli};
shape current_shape;

This is my other class

这是我的另一堂课

class Shapemaker
{
public:

    CDrawView view;
    static void Create(CDrawView::shape )
    {
        if(view.current_shape == view.line)
        {
            view.m_shape.reset(new Line());
        }
        else if(view.current_shape == view.rect)
        {
            view.m_shape.reset(new Rect());
        }
    }
}

What's the best practice to avoid this error

避免此错误的最佳做法是什么

回答by Joseph Mansfield

First of all, since the function is static, it doesn't have access to view. That's because viewis a non-static member of Shapemaker, so is only associated with specific instances o Shapemaker. Either viewneeds to be staticor the Createfunction shouldn't be. The other alternative is that viewshouldn't be a member and should be created inside the Createfunction.

首先,由于函数是static,它无权访问view. 那是因为view是 的非静态成员Shapemaker,所以仅与特定实例 o 相关联Shapemaker。无论是view需要被staticCreate功能不应该。另一种选择是它view不应该是成员,而应该在Create函数内部创建。

Also, the enum constants' names are within the scope of the CDrawViewclass and are accessed through the class name like so:

此外,枚举常量的名称在CDrawView类的范围内,可以通过类名访问,如下所示:

if(view.current_shape == CDrawView::line)

The .operator is for accessing a non-static member of an object. viewdoes not have a non-static member called lineor rect.

.运算符用于访问对象的非静态成员。view没有名为lineor的非静态成员rect

回答by taocp

viewis a non-static object of class CDrawView, Createis static function of ShapeMakerclass, there will be no instance of viewif you do not construct an object of ShapeMakerwhile Createis not associated with any objects of ShapeMaker. You cannot use nons-tatic members inside a static member function.

view是类CDrawView的非静态对象,Create是类的 静态函数,如果不构造对象,则不ShapeMaker会有实例viewShapeMakerCreate与ShapeMaker的任何对象都没有关联。您不能在静态成员函数中使用非静态成员。