【问题标题】:public inherited template friend classes公共继承的模板朋友类
【发布时间】:2011-11-17 11:01:25
【问题描述】:

如果我有这种层次结构:

#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;
}

为什么我需要在 typeB(int size) 构造函数中指定“this->x_ = new T[size]”而不是“x_ = new T[size]”来编译这段代码?

编译器告诉我的是它无法解析 x_ 的类型:

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

如果 typeB 是 typeA 的朋友,它应该可以公开访问 typeA 的属性。如果我尝试使用非模板类,它会起作用:

#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 和 typeB 是一种列表容器:您认为这种关系的动机是什么(公共继承 + 朋友,如果需要直接访问,则将 x_ 和 size_ 作为受保护的属性)?

【问题讨论】:

    标签: c++ templates inheritance public


    【解决方案1】:

    首先,成员x_ 是基类的私有成员。在这里友谊不会有帮助,因为您试图通过继承访问成员。

    即使您将其设为受保护或公开,模板基类的成员也不会自动在派生类中可见。

    解决办法是:

    1. 明确使用this-&gt;

       this->x_ = new int[size];
      
    2. 或将名称带入派生类范围:

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

      那你就可以写了

       x_ = new int[size];
      

    【讨论】:

    • 即使模板类是朋友也有效?
    • 我的意思是,如果私有属性在 typeA 中声明为 protected 可能会更容易,在这种情况下,如果继承是公共的,则可以通过 typeB 方法直接处理它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多