编译D&D六边形网格程序时遭遇Error code C2768错误求助
解决D&D六边形网格开发中的C2768编译错误
嘿,我看到你在折腾D&D跑团的交互式六边形网格,刚上手就遇到C2768错误,太懂这种头大的感觉了!咱们一步步来拆解问题,搞定它。
先搞懂C2768是什么
这个错误是Visual Studio(MSVC编译器)特有的,通常指向两种情况:
- 代码有未完成的语法(比如你没写完的函数),导致编译器无法解析;
- 结构体/类里的
const成员初始化或拷贝出了问题,MSVC对const成员的处理比其他编译器更严格。
你的代码里的核心问题
1. 未完成的pixel_to_hex函数
看你贴的代码,最后一行停在double q = M.b0 * pt.x + M.b1 * ,明显没写完!这会直接触发语法错误,编译器根本不知道你要干嘛。根据六边形网格的标准逻辑,完整的函数应该是这样的:
// Converts pixel coordinates to cell coordinates, use with hex_round function FractionalHex pixel_to_hex(Layout layout, Point p) { Orientation M = layout.orientation; Point size = layout.size; Point origin = layout.origin; Point pt = Point((p.x - origin.x)/size.x, (p.y - origin.y)/size.y); double q = M.b0 * pt.x + M.b1 * pt.y; double r = M.b2 * pt.x + M.b3 * pt.y; return FractionalHex(q, r, -q - r); }
2. const成员的拷贝构造问题
你所有的结构体(Hex、Point、Orientation等)都用了const成员,MSVC有时候无法自动生成正确的拷贝构造函数,这就是C2768错误的主要根源。解决方法是给每个带const成员的结构体显式添加拷贝构造函数:
比如Hex结构体修改后:
// Stores hex (cube) coordinates of a cell struct Hex { const int q, r, s; // 基础构造函数 Hex(int q_, int r_, int s_): q(q_), r(r_), s(s_) { if (q + r + s != 0) throw "q + r + s must be 0"; } // 方便的双参数构造(可以把你注释掉的版本加回来) Hex(int q_, int r_): q(q_), r(r_), s(-q_ - r_) {} // 显式拷贝构造,解决MSVC的C2768问题 Hex(const Hex& other) : q(other.q), r(other.r), s(other.s) {} };
同样的,给其他结构体也加上拷贝构造:
// Stores pixel coordinates struct Point { const double x, y; Point(double x_, double y_): x(x_), y(y_) {} Point(const Point& other) : x(other.x), y(other.y) {} }; // Stores fractional hex coordinates when converted from pixel coordinates struct FractionalHex { const double q, r, s; FractionalHex(double q_, double r_, double s_) : q(q_), r(r_), s(s_) { if (round(q + r + s) != 0) throw "q + r + s must equal 0"; } FractionalHex(const FractionalHex& other) : q(other.q), r(other.r), s(other.s) {} }; // Stores orientation of a cell struct Orientation { const double f0, f1, f2, f3; const double b0, b1, b2, b3; const double start_angle; // in multiples of 60deg Orientation(double f0_, double f1_, double f2_, double f3_, double b0_, double b1_, double b2_, double b3_, double start_angle_): f0(f0_), f1(f1_), f2(f2_), f3(f3_), b0(b0_), b1(b1_), b2(b2_), b3(b3_), start_angle(start_angle_) {} Orientation(const Orientation& other) : f0(other.f0), f1(other.f1), f2(other.f2), f3(other.f3), b0(other.b0), b1(other.b1), b2(other.b2), b3(other.b3), start_angle(other.start_angle) {} }; // Stores layout information of a cell struct Layout { const Orientation orientation; const Point size; const Point origin; Layout(Orientation orientation_, Point size_, Point origin_): orientation(orientation_), size(size_), origin(origin_) {} Layout(const Layout& other) : orientation(other.orientation), size(other.size), origin(other.origin) {} };
最后一步:重新编译
把上面的修改做完后,先解决了语法错误,再搞定const成员的拷贝问题,C2768错误应该就消失了。
另外提个小建议:你注释掉的Hex(int q_, int r_)构造函数非常实用,加回来后创建六边形坐标会方便很多,不用每次都手动算s的值。
你刚开始接触这个就能跟着专业指南走,已经超棒了!D&D的交互式网格做完肯定超酷,加油!
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

