Renaming class members by inheriting a class in C ++

I would like to “rename” some members of my class ofVec4f.

I know this is not possible in strict C ++, but can I create a new class that inherits from my class and declare new members that are aliases or pointers to the original elements?

I tried the following:

class ofVec4fGraph : public ofVec4f {

    public :
        float& minX;
        float& maxX;
        float& minY;
        float& maxY;

        ofVec4fGraph(float _minX,float _maxX, float _minY, float _maxY )
                    : minX(_minX), maxX(_maxX), minY(_minY), maxY(_maxY)
                    { ofVec4f(_minX, _maxX, _minY, _maxY); };

    };
+4
source share
3 answers

Your class should be:

class ofVec4fGraph : public ofVec4f {
public :
  float& minX;
  float& maxX;
  float& minY;
  float& maxY;

  ofVec4fGraph(float _minX,float _maxX, float _minY, float _maxY )
                    : ofVec4f(_minX, _maxX, _minY, _maxY), minX(x), maxX(y), minY(z), maxY(w)
     {};

};

Designer chain is not possible in C++. You use the initialization list to initialize the base class.

Now you can use this as:

ofVec4fGraph obj;
fun1(obj.x, obj.y);
fun2(obj.maxX, obj.minY);
+2
source

, , .

#include <iostream>

class CBase
{
public:
    CBase() : a(0), b(0), c(0) {}
    CBase(int aa, int bb, int cc) : a(aa), b(bb), c(cc) {}
    int a, b, c;
};

class CInterface
{
public:
    CInterface(CBase &b) 
    : base(b), x(b.a), y(b.b), z(b.c) 
    {
    }
    int &x, &y, &z;
private:
    CBase &base;
};

int main() 
{
    CBase      base(1, 2, 3);
    CInterface iface(base);

    std::cout << iface.x << ' ' << iface.y << ' ' << iface.z << std::endl;
    std::cout << base.a << ' ' << base.b << ' ' << base.c << std::endl;

    iface.x = 99;
    base.c = 88;

    std::cout << iface.x << ' ' << iface.y << ' ' << iface.z << std::endl;
    std::cout << base.a << ' ' << base.b << ' ' << base.c << std::endl;

    return 0;
}
+5
Is not à job for inherited class ? 

.

, , . , , . , . , @Michael J, .

class Base { protected: int x; };
class Derived: private Base { 
 public:
  int getValue(){ return x;} // name the method whatever you like.
};

0

Source: https://habr.com/ru/post/1540698/


All Articles