第一次学习c++成员模板,遇到了编译不通过的问题,我想知道怎么解决
#include <iostream>
using namespace std;
template<class T>
class bate
{
private:
template<class V>
class hold
{
private:
V val;
public:
hold(V v = 0) :val(v) {}
void show()const { cout << val << endl };
V Value()const { return val };
};
hold<T>q;
hold<int>n;
public:
bate(T a,int b):q(a),n(b){}
void Show() { q.show(); n.show(); }
};
void show()const { cout << val << endl };
V Value()const { return val };
分号在括号里面!
void show()const { cout << val << endl; }
V Value()const { return val; }
还有,类的定义不能嵌套
template<class V>
class hold
{
private:
V val;
public:
hold(V v = 0) :val(v) {}
void show()const { cout << val << endl };
V Value()const { return val };
};
这个要写在class bate定义的前面
不知道你这个问题是否已经解决, 如果还没有解决的话:问题代码中的编译错误是由于类模板Bate内部的成员模板Hold没有被正确实例化导致的。解决这个问题的方法是将成员模板Hold的定义移到类模板Bate外部,或者将成员模板Hold声明为Bate的友元。
以下是两种修复方案:
方案一:将成员模板Hold的定义移到类模板Bate外部
#include <iostream>
using namespace std;
template<class T>
class Hold
{
private:
T val;
public:
Hold(T v = 0) : val(v) {}
void show() const { cout << val << endl; }
T Value() const { return val; }
};
template<class T>
class Bate
{
private:
Hold<T> q;
Hold<int> n;
public:
Bate(T a, int b) : q(a), n(b) {}
void Show() { q.show(); n.show(); }
};
方案二:将成员模板Hold声明为Bate的友元
#include <iostream>
using namespace std;
template<class T>
class Bate
{
private:
template<class V>
friend class Hold;
template<class V>
class Hold
{
private:
V val;
public:
Hold(V v = 0) : val(v) {}
void show() const { cout << val << endl; }
V Value() const { return val; }
};
Hold<T> q;
Hold<int> n;
public:
Bate(T a, int b) : q(a), n(b) {}
void Show() { q.show(); n.show(); }
};
这两种修复方案都可以使代码编译通过。具体使用哪种方案取决于你的实际需求。