How to invoke the operator of the private base class?

P

PengYu.UT

I try to invoke the [] operator of the base class.

** line doesn't work. But *** line works. However, *** lines becomes
problematic with multiple inheritance is used for "derived". ****
works, but it is a little bit cumbersome. I'm wondering if there any
way to make ** works?


#include <iostream>
#include <cstring>

class base {
public:
int operator[](int i) {
return i;
}
int get(int i) {
return i;
}
};

class derived : private base {
public:
derived(int i) {
std::cout << "base: " << base << std::endl; //error
**
std::cout << "base: " << (*this) << std::endl; //no error
***
std::cout << "base: " << base::eek:perator[](i) << std::endl;//
no error ****
std::cout << "base.get(i): " << base::get(i) << std::endl;
}
};

int main(int argc, char *argv[])
{
derived a(10);
}
 
V

Victor Bazarov

I try to invoke the [] operator of the base class.

** line doesn't work.

The syntax "[blah]" is only applicable to _expressions_, and further
only to those that evaluate to objects of classes that overload the
operator[] or to pointers.

The syntax "[blah]" is not applicable to _types_. "base" is a *type*.
But *** line works.

Of course. "(*this)" is an *object* of type that overloads op[] (by
inheriting the base's one).
However, *** lines becomes
problematic with multiple inheritance is used for "derived".

What do you mean by that? You can always static_cast your 'this' to
avoid ambiguity.
****
works, but it is a little bit cumbersome. I'm wondering if there any
way to make ** works?
No.

#include <iostream>
#include <cstring>

class base {
public:
int operator[](int i) {
return i;
}
int get(int i) {
return i;
}
};

class derived : private base {
public:
derived(int i) {
std::cout << "base: " << base << std::endl; //error
**
std::cout << "base: " << (*this) << std::endl; //no error
***
std::cout << "base: " << base::eek:perator[](i) << std::endl;//
no error ****
std::cout << "base.get(i): " << base::get(i) << std::endl;
}
};

int main(int argc, char *argv[])
{
derived a(10);
}



V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top