質問

In my C++ program, I want to create an object that has properties like width, height, area, etc. I also want to declare methods that use and update this properties.

I want the methods that "set" and "get" the propery "width" listed somehow in a header, namespace, or child class (anyway is possible) named WidthManipulator.

The reason I want to create my structure this way is I want to use "get" name for another method of another class, like HeightManipulator.

But for nested classes I get the "illegal call of non-static member function" error for Rectangle::WidthManipulator::Get(). I also don't want to create Manipulator objects as these classes don't have properties, just methods that are using and updating parent properties... One more thing, I want to use void returns for a good reason of my own.

class Rectangle{
public:
int width,height;
int area;
int widthreturned;

    class WidthManipulator{
    public:
    void Set(int x){width = x;} 
    void Get(){widthreturned = width};
    };
};

How can I approach to my problem ? What should be my structure ?

役に立ちましたか?

解決 2

Am not sure why you want to structure your class manipulator this way, but to understand the mechanism of the Inner class consider that for the Inner class to access OUter class members, outer class should declare Inner as a friend:

class Outer
{ 
   int area;
   class Inner1;
   friend class Outer::Inner1;
   class Inner1 
   {
       Outer* parent;
   public:
       Inner1(Outer* p) : parent(p) {}
       void Set(int x){p->area= x;} 

   } inner1;
   // ... more stuff
};

If you want to check out with more detail, I recommend you to look at the design pattern example Chapter 11 Vol 2 Thinking in C++

他のヒント

The inner class in C++ is not like it is in Pascal. It's just paled in the "namespace" of the outer class, but no other thing is changed. It sees only its own members, and the instance is unrelated to the outer one.

If you want the relation, you must pass an instance of the outer somehow, say in the constructor. Then you can access members through that pointer or reference.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top