C++ getters/setters coding style

前端 未结 8 1431
小蘑菇
小蘑菇 2020-11-27 10:41

I have been programming in C# for a while and now I want to brush up on my C++ skills.

Having the class:

class Foo
{
    const std::string& name         


        
相关标签:
8条回答
  • 2020-11-27 11:42

    From the Design Patterns theory; "encapsulate what varies". By defining a 'getter' there is good adherence to the above principle. So, if the implementation-representation of the member changes in future, the member can be 'massaged' before returning from the 'getter'; implying no code refactoring at the client side where the 'getter' call is made.

    Regards,

    0 讨论(0)
  • 2020-11-27 11:43

    Collected ideas from multiple C++ sources and put it into a nice, still quite simple example for getters/setters in C++:

    class Canvas { public:
        void resize() {
            cout << "resize to " << width << " " << height << endl;
        }
    
        Canvas(int w, int h) : width(*this), height(*this) {
            cout << "new canvas " << w << " " << h << endl;
            width.value = w;
            height.value = h;
        }
    
        class Width { public:
            Canvas& canvas;
            int value;
            Width(Canvas& canvas): canvas(canvas) {}
            int & operator = (const int &i) {
                value = i;
                canvas.resize();
                return value;
            }
            operator int () const {
                return value;
            }
        } width;
    
        class Height { public:
            Canvas& canvas;
            int value;
            Height(Canvas& canvas): canvas(canvas) {}
            int & operator = (const int &i) {
                value = i;
                canvas.resize();
                return value;
            }
            operator int () const {
                return value;
            }
        } height;
    };
    
    int main() {
        Canvas canvas(256, 256);
        canvas.width = 128;
        canvas.height = 64;
    }
    

    Output:

    new canvas 256 256
    resize to 128 256
    resize to 128 64
    

    You can test it online here: http://codepad.org/zosxqjTX

    PS: FO Yvette <3

    0 讨论(0)
提交回复
热议问题