F
Francois Grieu
Hello, I know C well, but not C++, and have a naive question.
I have a class defined by a library that I do not want to modify;
in my case the mpz_class of gmpxx.h (see <http://gmplib.org> ).
I want to add a member function to this class, without the hassle
of writing something for each existing function of that class.
I can make a new class with a new name, and do not need to add
any field. If have tried the following and it nearly works:
#include <iostream>
using namespace std;
#include <gmpxx.h>
// attempt at a straight extension of gmpxx's mpz_class
class myz_class : public mpz_class {
public:
// smallest n such that 2^^n is greater than absolute value
mp_bitcnt_t bitlen() {
mp_bitcnt_t n = mpz_sgn(get_mpz_t());
if (n!=0)
n = mpz_sizeinbase(get_mpz_t(), 2);
return n;
};
};
int main (void)
{
mpz_class p;
myz_class y;
p = 0;
// y = 0; // does not compile, error: no match for 'operator='
for (int i=0; i<5; ++i)
{
cout
<< "# p=" << p
<< " abs(p)=" << abs(p)
<< " y=" << y
<< " abs(y)=" << abs(y)
<< " bitlen(y)=" << y.bitlen()
<< "\n";
++p;
++y; // works!
}
return 0;
}
I have two problems:
1) it appears that the overloaded operator = did not make it from
mpz_class to myz_class even though operator ++ did.
2) short of using a macro, how do I change things in order to
write bitlen(y) much like I write abs(y)?
TIA,
Francois Grieu
I have a class defined by a library that I do not want to modify;
in my case the mpz_class of gmpxx.h (see <http://gmplib.org> ).
I want to add a member function to this class, without the hassle
of writing something for each existing function of that class.
I can make a new class with a new name, and do not need to add
any field. If have tried the following and it nearly works:
#include <iostream>
using namespace std;
#include <gmpxx.h>
// attempt at a straight extension of gmpxx's mpz_class
class myz_class : public mpz_class {
public:
// smallest n such that 2^^n is greater than absolute value
mp_bitcnt_t bitlen() {
mp_bitcnt_t n = mpz_sgn(get_mpz_t());
if (n!=0)
n = mpz_sizeinbase(get_mpz_t(), 2);
return n;
};
};
int main (void)
{
mpz_class p;
myz_class y;
p = 0;
// y = 0; // does not compile, error: no match for 'operator='
for (int i=0; i<5; ++i)
{
cout
<< "# p=" << p
<< " abs(p)=" << abs(p)
<< " y=" << y
<< " abs(y)=" << abs(y)
<< " bitlen(y)=" << y.bitlen()
<< "\n";
++p;
++y; // works!
}
return 0;
}
I have two problems:
1) it appears that the overloaded operator = did not make it from
mpz_class to myz_class even though operator ++ did.
2) short of using a macro, how do I change things in order to
write bitlen(y) much like I write abs(y)?
TIA,
Francois Grieu