我的代码有问题。我有两个类,Run和Robot,我希望Robot类型的对象更改Run类型的对象的私有成员。具体地说,我想在下面的代码中增加'x‘的值。
弹出以下错误:
错误:未在此范围内声明“getX”错误:未在此范围内声明“getX”
我已经用箭头(<-)精确地指出了发生错误的行。下面的代码只是一个测试,只是为了学习如何在项目中使用'friend‘关键字。
#include <iostream>
#include <vector>
using namespace std;
class Robot;
class Run{
friend class Robot;
private:
int x;
vector<Robot*>robots;
public:
Run();
vector<Robot*>*getRobots();
void createRobot();
void movAll();
void setX(int);
int getX();
};
class Robot{
friend class Run;
public:
Robot();
void movingRobot();
};
Run::Run(){}
vector<Robot*>*Run::getRobots(){return &robots;}
void Run::createRobot(){getRobots()->push_back(new Robot);setX(1);}
void Run::movAll(){getRobots()->at(0)->movingRobot();}
int Run::getX(){return x;}
void Run::setX(int c){x=c;}
Robot::Robot(){}
void Robot::movingRobot(){setX(getX()+1);} <-------------------------
int main(){
Run Sim;
Sim.createRobot();
Sim.movAll();
}使用'friend‘关键字肯定会对我的项目有所帮助,所以我正在尝试了解如何使用它。
发布于 2013-12-15 02:24:45
您只是调用getX()和setX(),就好像它们是Robot的方法一样。您需要对Run的一个实例调用该函数,在本例中,您不需要它成为朋友,因为getX()无论如何都是公共的。
也就是说,您是否希望每个机器人都有一个您想要递增的x值?在这种情况下,您需要它成为Robot的成员,而不是Run。
如果你想让Run有一个所有Robot实例都可以访问和修改的x值,那么只需将x设为静态的,然后直接访问它,而不是调用公共方法,因为这不需要另一个类成为朋友。
发布于 2013-12-15 02:26:35
您调用了getX,就好像它是Robot类的函数一样。你需要一个run对象来调用它:
run.getX()发布于 2013-12-15 03:48:12
好的,您可以从Robot类中删除getX()函数,因为它目前没有代码体,并且对于内部使用,robot类总是可以利用它的X变量。Run不需要friend class Robot,因为Robot不需要在Run中查找任何内容,并且由于Run包含指向Robot实例的指针向量,因此它可以通过查看向量的内容来访问Robot实例的任何值(例如,myRunInstance.getRobots()[1]->getX()将返回robot向量中第二个机器人的x值)。
现在,如果getX函数要保留在Run类中,则它必须稍有不同:您将需要指定一种方法,使其收集Robot类的特定实例的信息,可能是从其Robot矢量中收集信息。我尊重你上面的代码,并在主代码中添加了一个小的概念集证明,让10个机器人使用moveall移动它们,然后将Johnny5设置到一个特殊的地方(因为他很特别:)大致是这样的:
#include <iostream>
#include <vector>
using namespace std;
class Run;
class Robot{
friend class Run; // allows the Run class to access all the private data as if it were its own
private:
int x;
public:
Robot() {};
void setX(int newX) { x= newX; }
int getX() { return x; }
void movingRobot() { x+=1; }
};
class Run{
private:
vector<Robot*> robots;
public:
Run(){};
vector<Robot*> *getRobots() { return &robots; }
void createRobot() { robots.push_back(new Robot()); robots.back()->x =1; }
void movAll() { for (int i=0;i<robots.size();i++){ robots[i]->movingRobot();} }
int getX(int robotPosition){ return robots[robotPosition]->x; } //uses the friend status to read directly from Robot class instances x
void setX(int rpos, int xval){ robots[rpos]->setX(xval); }
};
int main()
{
Run *Sim = new Run();
for (int i =0; i< 10; i++)
{
Sim->createRobot();
Sim->setX(i,i); // uses the Run setX
std::cout << "Robot " << i << "(starting position): " << Sim->getRobots()->at(i)->getX() << std::endl;
}
Sim->movAll();
// lets move Johnny 5 to 55 as well...
(Sim->getRobots()->at(4))->setX(55); // uses the robot setx
for (int i=0; i< 10; i++)
{
std::cout << "Robot " << i << "(final position): " << Sim->getRobots()->at(i)->getX()<< std::endl;
}
return 0;
}还可以通过Ideone上的示例输出查看源代码
https://stackoverflow.com/questions/20586668
复制相似问题