继承类c ++中的常量成员

时间:2016-04-22 14:19:28

标签: c++ inheritance

大编辑:

我有一个代码,我必须使用_elemente(它是一个向量)在一个继承的类中添加一个常量成员。不要在继承的类中添加成员,只需使用_elemente即可。在每个继承的类中(让我们说B,C,D和E)我没有MAX_VAL1,MAX_VAL2,依此类推,具有不同的值。 我试过了:

#include <iostream>
#include <iomanip>
#include <vector>
typedef unsigned int Uint;
typedef vector<Uint> TVint;
typedef vector<Uint>::const_iterator TIterator;

class A
{
protected:
Uint _count;
TVint _elemente;
public:
//
};

class B : public A
{
    const int MAX_VAL;
};

但它有一名成员,我不必在继承的班级中拥有一名成员。

这里的所有代码:

.h: http://pastebin.com/P3TZhWaV
.cpp: http://pastebin.com/ydwy2L5a

继承类的工作是使用常量成员完成的。

if MAX_VAL1 < count
{
throw Exception() {}
}
 if (_elemente.size() == 0) // As _elemente is a vector from STL
{
    _elemente.push_back(0);
}
for (int i = _elemente.size(); i < count; i++)
{
    _elemente.push_back(_elemente[i * (i+1) / 2]);
}
}

我不认为这是正确的,因为我必须使用来自STL的Vector,而且我并不认为这是因为应该添加未声明实际成员的继承类的常量成员。 谢谢你的帮助。

4 个答案:

答案 0 :(得分:1)

当你写的时候

class B : public A
{
    const int MAX_VAL;
};

您希望B&C的班级实例能够以当前的方式保持什么价值? 您是否尝试将ctor添加到B(将MAX_VAL初始化为某个精确值),以便整个类定义应该像

class B : public A
{
    const int MAX_VAL;
public:
    B(int max_val):MAX_VAL(max_val) {}
};

此外,上面的代码显示了许多未解答的问题。其中一些:

  • 你真的需要它成为会员吗?将其标记为“静态”&#39; (static const int MAX_VAL = 5)。这意味着,每个B的实例MAX_VAL都相等
  • 所有类型的重定义看起来都不重要。如果你使用内在类型和自动怎么办?
  • 通常一个人不会将size()与0进行比较 - 只需调用empty()。

您是否尝试过阅读Stroustrup或Lippman?

答案 1 :(得分:1)

您可以使用虚拟功能,如下所示:

    class A
    {

        virtual int max_val() const = 0;

        protected:
        Uint _count;
        TVint _elemente;

        public:
        //
    };

    class B : public A
    {
        int max_val() const { return 42; }
    };


    if ( max_val() < _count ) ...

答案 2 :(得分:1)

基于其他注释,您似乎想要一个可在基类中访问的const数,它可以根据派生类具有不同的值。你可以这样做:https://ideone.com/JC7z1P

输出: 答:50 B:80

#include <iostream>
using namespace std;

class Base
{
private:
    const int aNumber;
public:
    // CTOR
    Base( const int _aNumber ) :
        aNumber( _aNumber ) {}

    // check value  
    int getNumber() const
    {
        return aNumber;
    }
};

class A : public Base
{
public:
    A() : Base( 50 ) {}
};

class B : public Base
{
public:
    B() : Base( 80 ) {}
};

int main() {
    A a;
    B b;

    std::cout << "A: " << a.getNumber() << std::endl;
    std::cout << "B: " << b.getNumber() << std::endl;

    return 0;
}

答案 3 :(得分:0)

如果要静态访问它,可以使用模板:

  • let g:NERDTreeCopyCmd= 'cp -r'提供对值的多态访问
  • ABase提供对值的静态访问
  • AB是使用示例

C
相关问题