关于模板类中,子类无法访问父类成员问题的解决方法

问题:

今天研究数据结构,按着书敲代码,发现子类中直接调用父类成员居然无法通过编译。

看了好久都没发现问题,尝试将父类private属性改为public,发现也是不行。

解决办法:

然后我想着用域作用符,居然可以。

在网上搜了一下,发现用this指针,也是可以解决这个问题的。

//
//  List.h
//  HelloWorld
//  csdn blog:http://blog.csdn.net/u012175089
//  Created by feiyin001 on 17/1/7.
//  Copyright (c) 2017年 FableGame. All rights reserved.
//

#ifndef __HelloWorld__List__
#define __HelloWorld__List__

namespace Fable
{
    template<typename Object>
    class List
    {
    private:
        struct Node
        {
            Object data;
        };
    public:
        class const_iterator
        {

        private:
            Node* current;
            Object& retrieve()const
            {
                return current->data;
            }
        };
        class iterator: public const_iterator
        {
        public:
            Object& operator*()
            {
                //return retrieve();  无法通过编译
                //return const_iterator::retrieve(); 可以通过编译
                return this->retrieve();
            }
            iterator* operator++()
            {
                //current = current->next;无法通过编译
                //const_iterator::current = const_iterator::current->next; 可以通过编译
                this->current = this->current->next;
                return *this;
            }
        };
     };
}
#endif /* defined(__HelloWorld__List__) */

原因:

对于一些编译器,例如gcc和xcode,在扫描模板类的定义的时候,就先确定每一个成员都是在哪里声明的。

但是VC++把这件事放倒了实例化的时候,而具体的顺序C++标准实际上是没有规定的。

我正在用的电脑是MacBook,xode是没有解决这个问题的,有空试试VS才行。

posted @ 2017-01-08 08:53  肥宝游戏  阅读(462)  评论(0编辑  收藏  举报