gpt4 book ai didi

c++ - 构造错误 : ‘data’ was not declared in this scope

转载 作者:行者123 更新时间:2023-11-28 04:35:07 25 4
gpt4 key购买 nike

我不知道为什么子类不能使用父类的变量。我曾经使用 java 但它不会出现在 Java 中。我是一个c++初学者;


父类

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

子类

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

错误:

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

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

它也发生在儿子函数中的变量'length'上。

最佳答案

复制自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.

关于c++ - 构造错误 : ‘data’ was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51691231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com