我想将一个struct类的全局实例添加到我的程序中,该服务器具有特殊含义。有效的MWE是
// Example program
#include <iostream>
constexpr int x_max = 3;
constexpr int y_max = 4;
typedef struct Position {
constexpr Position(int x, int y) : x(x), y(y) {};
int x;
int y;
inline bool operator!=(const Position &rhs) const {
return (x != rhs.x || y != rhs.y);
}
inline bool inside_grid(const Position &empty) const {
return (x >= 0 && x < x_max && y >= 0 && y < y_max && *this != empty);
}
} Position;
constexpr Position empty = Position(1,1);
int main()
{
Position p1 = Position(2,3);
Position p2 = Position(1,1);
std::cout << "p1.inside_grid(empty) = " << p1.inside_grid(empty) << " and p2.inside_grid(empty) = " << p2.inside_grid(empty) << std::endl;
}
全局常量empty
必须传递给方法inside_grid
的每次调用,这让我想到如果我可以在程序开头声明全局并修改inside_grid
没有采取任何参数的方法:
// Example program
#include <iostream>
struct Position;
constexpr Position empty = Point(1, 1);
constexpr int x_max = 3;
constexpr int y_max = 4;
typedef struct Position {
constexpr Position(int x, int y) : x(x), y(y) {};
int x;
int y;
inline bool operator!=(const Position &rhs) const {
return (x != rhs.x || y != rhs.y);
}
inline bool inside_grid() const {
return (x >= 0 && x < x_max && y >= 0 && y < y_max && *this != empty);
}
} Position;
int main()
{
Position p1 = Position(2,3);
Position p2 = Position(1,1);
std::cout << "p1.inside_grid() = " << p1.inside_grid() << " and p2.inside_grid() = " << p2.inside_grid() << std::endl;
}
问题是由于我无法理解的错误,这将无法编译:
error: variable 'constexpr const Position empty' has initializer but incomplete type
error: invalid use of incomplete type 'struct Position'
可以解决这个问题吗?
答案 0 :(得分:2)
您可以转发声明您的inside_grid()
方法,并在创建empty
后稍后进行定义:
// Example program
#include <iostream>
struct Position;
constexpr int x_max = 3;
constexpr int y_max = 4;
typedef struct Position {
constexpr Position(int x, int y) : x(x), y(y) {};
int x;
int y;
inline bool operator!=(const Position &rhs) const {
return (x != rhs.x || y != rhs.y);
}
bool inside_grid() const;
} Position;
constexpr Position empty = Position(1, 1);
inline bool Position::inside_grid() const {
return (x >= 0 && x < x_max && y >= 0 && y < y_max && *this != empty);
}
int main()
{
Position p1 = Position(2,3);
Position p2 = Position(1,1);
std::cout << "p1.inside_grid() = " << p1.inside_grid() << " and p2.inside_grid() = " << p2.inside_grid() << std::endl;
}