0

I don't know that why the son class can't use the variable from the parent class. I used to use java but it does not occur in Java. I am a c++ beginner;


the parent class

#include <iostream>

template<class T>
class List{
protected:
    int length;
    T *data;
public:
    List() {
        length = 0;
        data = nullptr;
        std::cout << "父类构造函数..." << std::endl;
    }

    virtual ~List() {
        length = 0;
        data = nullptr;
        std::cout << "父类析构函数..." << std::endl;
    }
}

the son class

#include "List.h"

template<class T>
class ArrayList : public List<T> {
private:
    const int INIT_SIZE = 10;
    const int INCREMENT_SIZE = 10;

    int maxSize;


public:
    ArrayList() {
        std::cout << "子类构造函数..." << std::endl;
        data = new T[INIT_SIZE];
        maxSize = INIT_SIZE;
    }

    virtual ~ArrayList() {
        std::cout << "子类析构函数..." << std::endl;
        maxSize = 0;
    }
}

error:

In constructor ‘ArrayList<T>::ArrayList()’:

error: ‘data’ was not declared in this scope
         data = new T[INIT_SIZE];
         ^~~~

It also occurred on the variable 'length' which in the son's functions.

何佳成
  • 3
  • 1

2 Answers2

1

Copied from C++ Super FAQ

  • Change the call from f() to this->f(). Since this is always implicitly dependent in a template, this->f is dependent and the lookup is therefore deferred until the template is actually instantiated, at which point all base classes are considered.

  • Insert using B<T>::f; just prior to calling f().

  • Change the call from f() to B<T>::f(). Note however that this might not give you what you want if f() is virtual, since it inhibits the virtual dispatch mechanism.

Community
  • 1
  • 1
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

Use this->data . This should fix your problems.