【问题标题】:Rename class members by inheriting class in C++通过在 C++ 中继承类来重命名类成员
【发布时间】:2014-07-03 22:01:15
【问题描述】:

我想“重命名”我班级的一些成员ofVec4f

我知道在严格的 C++ 中这是不可能的,但我可以创建一个继承自我的类的新类并声明新成员,这些新成员是原始成员的别名或指针吗?

我尝试了以下方法:

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); };

    };

【问题讨论】:

  • 你应该在初始化列表中调用基础构造函数:...) : ofVec4f(_minX, _maxX, _minY, _maxY), ...
  • 括号里的地方做错了吗?
  • 在 Java 中可以,但在 C++ 中,您的代码只是在堆栈上创建类型为 Vec4f 的临时值。
  • 很好的解释 ;-)
  • 请注意,每个引用将占用sizeof(float*) 更多字节,访问它们将需要取消引用指针。如果可能,考虑使用成员函数 - 没有性能损失,编译器足够聪明,可以内联函数。

标签: c++ class inheritance rename alias


【解决方案1】:

我想这可能是你想要的。

#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;
}

【讨论】:

    【解决方案2】:

    你的班级应该是:

    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)
         {};
    
    };
    

    构造函数链接C++ 中是不可能的。您使用初始化列表来初始化基类。

    您现在可以将其用作:

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

    【讨论】:

    • 我可以用结构做吗?会是普通的旧数据吗?
    • 不幸的是,它不适用于 POD :(。我测试过该类包含每个引用的额外 4 字节指针 - Visual Studio。
    【解决方案3】:
    Is not à job for inherited class ? 
    

    不一定。

    Proper Inheritance 规定您仅在 派生类 可替代基类公开 继承。在这种情况下,您根据基类实现派生类,这里首选的方法是使用private inheritance,或者更好的是object composition。和composition is better than inheritance。您应该使用@Michael J 描述的方法,或者使用私有继承。

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

    也学why public data member is bad

    【讨论】:

    • 我的班级 ofVec4f,来自 openFrameworks main.h 标头,因为他的成员已经公开
    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2010-12-29
    • 2010-11-26
    • 2019-03-23
    相关资源
    最近更新 更多