gpt4 book ai didi

模板对象的 C++ 继承(G++ 编译器)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:42 27 4
gpt4 key购买 nike

#include <cstdlib>
#include <vector>
#include <iostream>

using namespace std;

class CFirstLevel {
public:
CFirstLevel (const string & _name): name (_name) {}
// ...

protected:

string name;

};

template <typename T>
class CSecondLevel: public CFirstLevel {
public:

CSecondLevel (const string & _name): CFirstLevel (_name) {}

virtual void PushBack (T) = 0;
virtual void Print (int I) {cout << data [I] << endl;}
// ...

protected:
vector<T> data;
};

template <typename A>
class CThirdLevel: public CSecondLevel<A> {
public:
CThirdLevel (const string & _name): CSecondLevel<A> (_name) {}

virtual void PushBack (A _value) {data.push_back (_value);}

};


int main ( void ) {

CThirdLevel<int> * pointer = new CThirdLevel<int> ("third");
pointer -> PushBack (111);

pointer -> Print (0);

return 0;

}

编译器返回错误:

main.cpp: 在成员函数‘virtual void CThirdLevel::PushBack(T)’中:

main.cpp:32:37: 错误:“数据”未在此范围内声明

哪里出了问题?是否可以使用这种继承?

最佳答案

问题出在 CTirdLevel 中。字段 data 无法从 CSecondLevel 解析。您可以通过更改

来解决此问题
virtual void PushBack (A _value) {data.push_back (_value);}

virtual void PushBack (A _value) {CSecondLevel<A>::data.push_back (_value);}

关于模板对象的 C++ 继承(G++ 编译器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16816843/

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