C ++使用const成员继承而不使用getter

时间:2016-11-22 20:03:10

标签: c++ oop inheritance

我正在尝试设计一个类,它提供了一个根据其属性之一执行某些操作的函数。我也想做同样的过程,但是使用另一个值,这就是我创建派生类并修改属性的原因。

首先,我创建了一个静态属性,因为该值不依赖于每个对象,而是依赖于类本身。或者,我不能继承静态属性并修改每个类'之一。

然后,我决定将我的属性放在const中以便能够使用继承。我做了一个简单的程序来向你展示我的问题。在这里,我希望foo显示调用方法的对象的值,而不是Parent的值。另外,我不想使用getter,因为我会在我的方法中多次使用变量,这是用于图像处理。

#include <iostream>

// Compile it with
// g++ -o child_test child_test.cpp -std=c++11

class Parent{   
    public:
        Parent() {}    
        virtual void foo(){
            printf("%d\n", this->bar);
        }    
    private:    
        const int bar = 0;    
};    

class Child : public Parent{    
    public:   
        Child() : Parent() {}
    private: 
        const int bar = 10;
};

int main(){    
    Parent * p = new Parent();
    p->foo(); // Output : 0

    Child * c = new Child();
    c->foo(); // Output : 0 ? How could it be 10 

    Parent * cp;
    cp = new Child();
    cp->foo(); // Output : 0 ? How could it be 10 
}

3 个答案:

答案 0 :(得分:4)

这不是语言的运作方式。该函数可能是虚函数,但成员变量(常量)不是。

如果要在基类中使用不同的值,请将其传递给构造函数。

class Parent{   
    public:
        Parent(int value = 0) : bar(value) {}    
        virtual void foo(){
            printf("%d\n", this->bar);
        }    
    private:    
        const int bar = 0;    
};    

class Child : public Parent{    
    public:   
        Child() : Parent(10) {}
};

答案 1 :(得分:2)

  

C-&GT; FOO(); //输出:0?怎么可能是10

您可以更改访问bar的方式。不要使其成为成员变量,而是使用返回值的virtual成员函数。

class Parent{   
    public:
        Parent() {}    
        virtual void foo(){
            printf("%d\n", this->bar());
        }    
    private:    
        virtual int bar() const
        {
           return 0;
        }
};    

class Child : public Parent{    
    public:   
        Child() : Parent() {}
    private: 
        virtual int bar() const
        {
           return 10;
        }
};

答案 2 :(得分:0)

  

C-&GT; FOO(); //输出:0?怎么可能是10

您有两个成员变量bar,一个在Parent类,一个在Child。您的foo功能不是纯虚拟,而Child类中的未被覆盖,因此默认情况下会调用Parent实现(已经有bar变量) - 这就是输出为0的原因。

如果覆盖foo类中的Child函数(例如,具有相同的foo函数),则输出为10.