error:a nonstatic member reference must be relative to a specific object
Solution 1
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.
Also, the enum constants' names are within the scope of the CDrawView
class and are accessed through the class name like so:
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
.
Solution 2
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.
user1665569
Updated on July 09, 2022Comments
-
user1665569 almost 2 years
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 myCDrawView
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