问题描述
==> 我试图恢复一个很长很长的代码,所以除了相关功能之外的所有其他功能都已经过测试并且正在运行!所有#include 也都可以
蚂蚁是:
#ifndef ANT_HPP
#define ANT_HPP
class Ant{
public:
Ant(Coord a,int n); //constructor: the coordonate of the ant,and its number
void deplace(Coord a); //an ant goes to coordonates a
Coord fCoord; //the coordonates of the Ant
int fNum; //a Number attributed to each ant };
#endif
所以,我在 Ant.cpp 中有这个:
void Ant::deplace(Coord a){ fCoord = a; }
和测试(使用 doctest)完美地工作:
TEST_CASE("test fourmis : "){
Ant f = Ant(Coord{2,3},3);
f.deplace(Coord{11,12});
CHECK(f.coord() == Coord{11,12}); }
void deplaceAnt(Ant f,Place a,Place b) {
p1.takeAnt(); //take an Ant away of a Place p1
f.deplace(p2.coord()); //the function that is not working :(
p2.putAnt(f); // put an Ant in a Place p2 }
place.hpp 就像:
#ifndef PLACE_HPP
#define PLACE_HPP
#include "Ant.hpp"
class Place{
public:
Place(Coord x); //constructor : create a Place from a Coordonate
int numAnt; //the number of the Ant on the Place
bool isAnt; //if there is an Ant or not
Coord Pcoord; //Coord of the Place }
#endif
这是不起作用的测试:
TEST_CASE("Place test : "){
Place q = Place(Coord{11,12});
Place p = Place(Coord{2,6});
Ant f = Ant(Coord{1,2},3)
q.putAnt(f);
deplaceAnt(f,q,p);
// f{1,2} must go from q{3,4} to p{2,6}
CHECK(f.fCoord == p.coord());
CHECK(q.isAnt == false);
CHECK(p.isAnt == true); }
这是编译后的消息:
TEST CASE: test Place :
place.cpp:206: ERROR: CHECK( f.fCoord == p.coord() ) is NOT correct!
values: CHECK( (1,2) == (2,6) )
place.cpp:207: ERROR: CHECK( q.isAnt == false ) is NOT correct!
values: CHECK( true == false )
place.cpp:209: ERROR: CHECK( p.isAnt == true ) is NOT correct!
values: CHECK( false == true )
===============================================================================
[doctest] test cases: 5 | 4 passed | 1 Failed | 0 skipped
[doctest] assertions: 67 | 62 passed | 5 Failed |
[doctest] Status: FAILURE!
我想知道为什么该函数在 file.cpp 中工作而不是在另一个中工作。 + Ant.cpp 中还有其他函数(我没有在这里展示),我在 Place.cpp 中重新使用了它们,并且它们带有 np... 很奇怪,不是吗?
解决方法
你的功能
void deplaceAnt(Ant f,Place a,Place b)
按值获取参数,这意味着它们是副本。对这些对象的更改不会影响原始对象。您需要通过引用传递它们:
void deplaceAnt(Ant& f,Place& a,Place& b)
因此,您正在对原始对象进行更改,而不是对副本进行更改。