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
error:a nonstatic member reference must be relative to a specific object
提问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::Shape
is 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 view
is a non-static member of Shapemaker
, so is only associated with specific instances o Shapemaker
. Either view
needs to be static
or the Create
function shouldn't be. The other alternative is that view
shouldn't be a member and should be created inside the Create
function.
首先,由于函数是static
,它无权访问view
. 那是因为view
是 的非静态成员Shapemaker
,所以仅与特定实例 o 相关联Shapemaker
。无论是view
需要被static
或Create
功能不应该。另一种选择是它view
不应该是成员,而应该在Create
函数内部创建。
Also, the enum constants' names are within the scope of the CDrawView
class 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. view
does not have a non-static member called line
or rect
.
该.
运算符用于访问对象的非静态成员。view
没有名为line
or的非静态成员rect
。
回答by taocp
view
is a non-static object of class CDrawView, Create
is static function of ShapeMaker
class, there will be no instance of view
if you do not construct an object of ShapeMaker
while Create
is not associated with any objects of ShapeMaker. You cannot use nons-tatic members inside a static member function.
view
是类CDrawView的非静态对象,Create
是类的 静态函数,如果不构造对象,则不ShapeMaker
会有实例view
,ShapeMaker
而Create
与ShapeMaker的任何对象都没有关联。您不能在静态成员函数中使用非静态成员。