鱼C论坛

 找回密码
 立即注册
查看: 1689|回复: 2

C++ 模板

[复制链接]
发表于 2023-10-6 14:46:04 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 hellomyprogram 于 2023-10-6 17:22 编辑

graphics.h
  1. namespace graph
  2. {
  3.         template <typename position_type = int>
  4.         class Dot
  5.         {
  6.                 public:
  7.                         position_type x = 0;
  8.                         position_type y = 0;
  9.         };

  10.         class Rect
  11.         {
  12.                 enum relative_pos
  13.                 {
  14.                         TopLeft = 0b0000,
  15.                         TopMiddle,
  16.                         TopRight,
  17.                         MiddleLeft = 0b0100,
  18.                         Center,
  19.                         MiddleRight,
  20.                         BottomLeft = 0b1000,
  21.                         BottomMiddle,
  22.                         BottomRight
  23.                 };
  24.                 public:
  25.                         Dot<> position = {0, 0};
  26.                         unsigned int width;
  27.                         unsigned int height;
  28.                         Rect(unsigned int, unsigned int);
  29.                         Rect(int, int, unsigned int, unsigned int);
  30.                         Dot<> get_absolute(relative_pos);
  31.                         Dot<> get_absolute(Dot<>);
  32.                         void set_absolute(relative_pos, Dot<>);
  33.                         Dot<> set_absolute(Dot<>, Dot<>);
  34.         };
  35. };
复制代码

graphics.cpp
  1. #include <graphics.h>
  2. Dot<> graph::Rect::get_absolute(relative_pos relative)
  3. {}
复制代码

编译器凭什么说 Dot 不是模板


Dot 前面没加 graph 命名空间
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-10-6 14:46:20 | 显示全部楼层
编译器认为  Dot  不是模板是因为在  graphics.cpp  文件中, get_absolute  函数的定义没有指定模板参数。在 C++ 中,模板类的成员函数的定义也需要指定模板参数。

要解决这个问题,可以将  get_absolute  函数的定义也改为模板函数,并指定相应的模板参数。修改后的代码如下:

  1. template <typename position_type>
  2. Dot<position_type> graph::Rect::get_absolute(relative_pos relative)
  3. {}
复制代码


这样编译器就能正确识别  Dot  是一个模板类,并且能够根据指定的模板参数进行实例化。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-6 14:46:33 | 显示全部楼层
编译器报错是因为在 graphics.cpp 文件中,Dot 类型没有提供模板参数。Dot 是一个模板类,因此在使用它时,需要提供相应的模板参数。在这个例子中,Dot 类型的默认模板参数是 int,所以你可以使用 Dot<int> 或者简写为 Dot<>

为了解决这个问题,你需要在 graphics.cpp 文件中的 get_absolute 函数定义中使用 Dot<> 类型。修改后的代码如下:

  1. #include <graphics.h>

  2. Dot<> graph::Rect::get_absolute(relative_pos relative) {
  3.     // 函数实现
  4. }
复制代码


请注意,你还需要在 graphics.hgraphics.cpp 文件中添加正确的命名空间,以便正确地引用 DotRect 类。在这个例子中,我假设你使用了 graph 命名空间。如果你使用了其他命名空间,请相应地进行修改。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 04:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表