问题描述
大编辑:
我有一个代码,我必须使用_elemente(这是一个向量)在继承的类中添加一个常量成员。不要在继承的类中添加成员,只需使用_elemente即可。在每个继承的类中(比如说B,C,D和E)我都有MAX_VAL1,MAX_VAL2等等,它们具有不同的值。
我试过:
I have a code in which I have to add a constant member in a inherited class by using _elemente (which is a vector). Not to add a member in the inherited classes, just by using _elemente. In every inherited classes (let's say B, C, D and E) I withh have MAX_VAL1, MAX_VAL2 and so on with different values.I tried:
#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;
};
但它有一个成员,我不需要在继承的类中拥有成员。
But it has a member and I don't have to have a member in the inherited class.
此处的所有代码:
.h: http://pastebin.com/P3TZhWaV
.cpp: http://pastebin.com/ydwy2L5a
继承类的工作是使用常量成员完成的。
The work from the inherited classes is done using that constant members.
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,我真的不认为这应该是添加未声明实际成员的继承类的常量成员。
感谢您的帮助。
I don't think that is correct as I have to use the Vector from STL and I don't really think that is the way the constant member from a inherited class without the actual member declared should be added.Thanks for your help.
推荐答案
基于其他注释,您似乎想要一个可在基类中访问的const数,它可以具有不同的值取决于派生类。你可以这样做:
Based on other comments it seems like you want a const number that is accessible in the base class which can have a different value depending on the derived class. You could achieve that like this: https://ideone.com/JC7z1P
输出:
A:50
B:80
output:A: 50B: 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;
}
这篇关于继承类c ++中的常量成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!