模板类继承模板类,子类看不到父类对象

问题重现

hello.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template <typename T>
class A {
protected:
T data_;
};

template <typename T>
class B : public A<T> {
public:
void test() {
std::cout << data_;
}
};

int main() {
std::cout << "hello world" << std::endl;
return 0;
}

出现以下错误:

1
2
3
4
hello.cpp: In member function ‘void B<T>::test()’:
hello.cpp:13:22: error: ‘data_’ was not declared in this scope
std::cout << data_;
^~~~~

解决方案

使用this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template <typename T>
class A {
protected:
T data_;
};

template <typename T>
class B : public A<T> {
public:
void test() {
std::cout << this->data_;
}
};

int main() {
std::cout << "hello world" << std::endl;
return 0;
}

使用父类类名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template <typename T>
class A {
protected:
T data_;
};

template <typename T>
class B : public A<T> {
public:
void test() {
std::cout << A<T>::data_;
}
};

int main() {
std::cout << "hello world" << std::endl;
return 0;
}

使用using

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

template <typename T>
class A {
protected:
T data_;
};

template <typename T>
class B : public A<T> {
using A<T>::data_;
public:
void test() {
std::cout << data_;
}
};

int main() {
std::cout << "hello world" << std::endl;
return 0;
}