C++类模板的数据成员为结构体模板,该结构体模板中有一成员为结构体模板,有大神能帮我解惑吗

Rufengi 2017-06-12 09:41:01
#include<iostream>
#include<string>
using namespace std;
template<typename A,typename B>
struct score
{
A math;
B English;
};

template <typename T>
struct student
{
string name;
T Score;
};

template <typename T>
class teacher
{
public:
student<T> info;
teacher()
{

}
void printf()
{
cout << info << endl;
}
friend ostream &operator<<(ostream &out, student <T> &my)
{
out << "\t" << my.name << "\t" << my.Score.English << "\t" << my.Score.math << endl;
return out;
}
};
int main()
{
student<score<int, int>> mystu = { "呵呵", { 100, 100 } };
teacher<student<score<int, int>>>mytea;
myteacher.printf();
system("pause");
return 0;
}
...全文
679 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Rufengi 2017-06-12
  • 打赏
  • 举报
回复
这个我能理解,就是不知道代码错在哪里,实现不了,改来改去还是错误的
幻夢之葉 2017-06-12
  • 打赏
  • 举报
回复
哪儿不懂? 模板的嵌套 student<score<int, int>> score用int,int进行实例化,score<int, int>为一个具体类型 然后再把这个类型当做student的模板参数 替换进去即: struct score { int math; int English; }; struct student { string name; score Score; }; class teacher { public: student info; }
Rufengi 2017-06-12
  • 打赏
  • 举报
回复
我明白了,谢谢!
Rufengi 2017-06-12
  • 打赏
  • 举报
回复
不好意思,刚刚又试了下,没错,我的问题,不过,你那个输出流重载不太理解,如果放在类中的话,那该怎么写呢
supergerm 2017-06-12
  • 打赏
  • 举报
回复
你的编译器问题吧?
Rufengi 2017-06-12
  • 打赏
  • 举报
回复
还是错误的啊,名字乱码
supergerm 2017-06-12
  • 打赏
  • 举报
回复

#include<iostream>
#include<string>
using namespace std;
template<typename A, typename B>
struct score
{
	A math;
	B English;

	friend ostream &operator<<(ostream &out, score &value)
	{
		out << value.math << "\t" << value.English << endl;
		return out;
	}
};

template <typename T>
struct  student
{
	string name;
	T Score;

	friend ostream &operator<<(ostream &out, student <T> &my)
	{
		out << "\t" << my.name << "\t" << my.Score << endl;
		return out;
	}
};

template <typename T>
class teacher
{
public:
	T info;
	teacher()
	{

	}

	teacher(T s)
	{
		info.name = s.name;
		info.Score.math = s.Score.math;
		info.Score.English = s.Score.English;
	}

	void printf()
	{
		cout << info << endl;
	}
};
int main()
{
	student<score<int, int>> mystu = { "呵呵", { 100, 100 } };

	teacher<student<score<int, int>>>mytea(mystu);
	mytea.printf();
	system("pause");
	return 0;
}

64,939

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧