拜托,我不知道为什么这个简单的代码被拒绝。
它给了我 2 个编译错误。
请帮帮我。 ????
I use 代码::块 20.03
我的编译器是GNU GCC
---移动.hpp---
class Move {
public:
Move();
Move(int, int);
public:
int from;
int to;
const static Move NONE = Move(0,-1); //error here
//undefined reference if I use
//const static Move NONE;
};
---移动.cpp---
#include "move.hpp"
Move::Move() {
this->from = 0;
this->to = 0;
}
Move::Move(int from, int to) {
this->from = from;
this->to = to;
}
---主.cpp---
#include <iostream>
#include "move.hpp"
int main(){
Move move = Move::NONE;//error here
std::cout << move.from << std::endl;
std::cout << move.to << std::endl;
return 0;
}
您应该为静态数据成员提供类外定义NONE
在源文件(如 move.cpp)中,它将起作用,因为此时该类已完成,如下所示:
move.hpp
#pragma once
class Move {
public:
Move();
Move(int, int);
public:
int from;
int to;
//declaration for NONE
const static Move NONE ;
//------------------------------^^------>no in class initializer here
};
move.cpp
#include "move.hpp"
//definition for Move::NONE
const Move Move::NONE = Move(0,-1);
Move::Move() {
this->from = 0;
this->to = 0;
}
Move::Move(int from, int to) {
this->from = from;
this->to = to;
}
工作演示 https://onlinegdb.com/n4x8Rwjiv
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)