简体   繁体   English

C ++软件架构和设计

[英]C++ software architecture and design

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. 在我的C ++程序中,我想创建一个具有宽度,高度,面积等属性的对象。我还想声明使用和更新此属性的方法。

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. 我希望以某种方式在名为WidthManipulator的标头,名称空间或子类(无论如何都可以)中列出“设置”和“获取”属性“ width”的方法。

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. 我要以这种方式创建结构的原因是,我想对另一个类的另一个方法(例如HeightManipulator)使用“ get”名称。

But for nested classes I get the "illegal call of non-static member function" error for Rectangle::WidthManipulator::Get(). 但是对于嵌套类,对于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. 我也不想创建Manipulator对象,因为这些类没有属性,只有正在使用和更新父属性的方法...还有一件事,由于我自己的一个很好的原因,我想使用void返回值。

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 ? 我的结构应该是什么?

The inner class in C++ is not like it is in Pascal. C ++中的内部类与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. 然后,您可以通过该指针或引用访问成员。

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: 不确定为什么要以这种方式构造类操纵器,但是要了解Inner类的机制,请考虑为使Inner类访问OUter类成员,外部类应将Inner声明为朋友:

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++ 如果您想更详细地了解一下,建议您看一下设计模式示例,第11章第2卷,C ++思维

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM