一道模板继承的C++题

来源:百度知道 编辑:UC知道 时间:2024/05/10 15:07:39
#include <iostream>
using namespace std;

template<int n = 1>
class Point
{
public:
void show()
{
for(int i = 0; i < n; ++i)
{
cout << 'b';
}
}
};

class Line : public Point<10>
{
};

int main()
{
Point<> pt;
Line ln;

cout << "A point: ";
pt.show();

cout << "\nA line: ";
ln.show();
cout<<endl;
return 1;
}
能不能给我一步一步讲一下~~~谢谢

#include <iostream>
using namespace std;

template<int n = 1> //////定义了模板 参数是一个int类型的数据 如果你不给参数 默认为1
class Point /////////类的定义 基类
{
public:
void show()
{
for(int i = 0; i < n; ++i) /////这里的n就是上面模板里的那个数
{
cout << 'b';
}
}
};

class Line : public Point<10> ///定义了另外的一个类 继承了point<10>////也就是说它的基类是一个n=10的基类
{
};

int main()
{
Point<> pt; ////这里定义了基类对象 没有给参数 所以基类就用了默认值 你给的默认值为1 所以也就是n=1了
Line ln; //////////定义了子类 但是这里的n=10 固定的 因为你固定声明了他的基类为10

cout << "A point: ";
pt.show(); ///////////输出

cout << "\nA line: ";
ln.show(); ////////////输出
cout<<endl;
return 1;
}

#include <iostream>
using namespace std;

template<int n = 1>
class Point
{
public:
void show()
{