简体   繁体   中英

public inherited template friend classes

If I have this kind of hierarchy:

#include <iostream>

using namespace std;

template<class T>
class typeB;

template<class T>
class typeA 
{
    // Private data
        T* x_;
        int size_;
    public:
        // Constructors
        typeA()
            : x_(0), size_(0)
        {
        };
        typeA(int size)
            : x_(0), size_(size)
        {
        }

        // Friend classes.
        friend class typeB<T>;
};

template<class T>
class typeB
: public typeA<T>  
{
    public:
        // Constructors
        typeB ()
        {
        };
        typeB (int size)
            : typeA<T>(size)
        {
            //this->x_ = new T[size];
            x_ = new T[size];
        }
};

int main()
{
    typeB<int> b(4);

    return 0;
}

why do I need to specify "this->x_ = new T[size]" in the typeB(int size) constructor instead of "x_ = new T[size]" to get this code to compile?

What the compiler tells me is that it cannot resolve the type of x_:

main.cpp: In constructor ‘typeB<T>::typeB(int)’:
main.cpp:42: error: ‘x_’ was not declared in this scope

If the typeB is a friend of typeA, it should have public access to typeA attributes. If I try this with non-templated classes, it works:

#include <iostream>

using namespace std;

class typeB;

class typeA 
{
    // Private data
        int* x_;
        int size_;
    public:
        // Constructors
        typeA()
            : x_(0), size_(0)
        {
        };
        typeA(int size)
            : x_(0), size_(size)
        {
        }

        // Friend classes.
        friend class typeB;
};

class typeB
: public typeA
{
    public:
        // Constructors
        typeB ()
        {
        };
        typeB (int size)
            : typeA(size)
        {
            x_ = new int[size];
        }
};

int main()
{
    typeB b(4);

    return 0;
}

typeA and typeB are kind of a list containers: what do you think would be the motivation for such kind of relationship (public inheritance + friends, vs having x_ and size_ as protected attributes if direct access is required)?

First of all, the member x_ is a private member of the base class. Here friendship is not going to help, since you're trying to access members through inheritance.

Even if you make it protected or public, the members of a template base class are not automatically visible in the derived class.

The solution are:

  1. Use this-> explicitly as,

      this->x_ = new int[size]; 
  2. Or bring the names into the derived class scope as:

      template<class T> class typeB : public typeA<T> { using typeA<T>::x_; //brings the name x_ into the class scope! //... 

    then you can write

      x_ = new int[size]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM