脚本宝典收集整理的这篇文章主要介绍了Cpp小作业-帮助理解Cpp的类,参数,函数,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
题目要求:
You are asked to create a C++ program that simulates the movements of two mobile robots. Call it main.cpp or similar.
简单来说,创建一个Robot的Class,为其添加命名,坐标,转向三项功能并打印这些参数。
作为一个只有JAVA基础从来没学过Cpp的彩笔,刚上手还确实有些难度,想框架3分钟,改bug3小时。
几个难住我的点
1.没有与这些操作匹配的 << 运算符
这个困扰了我很久,最后发现错的非常离谱。
忘记了加
#include<string>
......
2. 非标准语法;请使用"&"来创建指向成员的指针
Bob.printStatus;
在这里,使用的应是成员函数,而非类的成员变量。
当使用class的成员函数时,VS并不会帮我们加上圆括号, 所以很多新人(比如我)就会忘记加上 ( ) 来表示函数调用。
不加括号的时候,也就是函数不传入参数的话(包括void),编译器会理解成函数指针,但是函数指针正确写法是
&Bob.printStatus;
因此便有了上面的错误提示。
来自: 错误 "xxxx":C++提示非标准语法;请使用 "&" 来创建指向成员的指针_勇搏风浪的博客-CSDN博客
解决了报错以后就很简单了,权当复习了一下JAVA,项目代码如下:
/* ID: 210110131 Name: Fangyuan Wei Date: 04/11/2021 */ #include <iostream> #include<string> using namespace std; class Robot { public: string robotname; //Robot name int xPosition; //Robot x-axis position int yPosition; //Robot y-axis position int directions = 0; //1 = right→+x, 2 = up→+y , 3 = left→-x, 4 = down→-y. Refer to Cartesian coordinate system Robot(string name, int xPos, int yPos, int direction) { robotname = name; xPosition = xPos; yPosition = yPos; directions = direction; } void moveForward(int step) { //Robot move forward switch (directions) { //different situation for steps case 1: xPosition = xPosition + step; break; case 2: yPosition = yPosition + step; break; case 3: xPosition = xPosition - step; break; case 4: yPosition = yPosition - step; break; } } void rotateClock() { //rotate clockwise if (directions != 1){ directions--; } else { directions = 4; } } void rotateCounterClock() { //rotate counterclockwise if (directions != 4){ directions++; } else { directions = 1; } } void printStatus() { //print status of robot string dirEN; switch (directions) //change the format of direction from numbers to words { case 1: dirEN = "Positive X direction"; break; case 2: dirEN = "Positive Y direction"; break; case 3: dirEN = "Negative X direction"; break; case 4: dirEN = "Negative Y direction"; break; default: break; } cout << "The robotname is " << robotname << "," << endl; cout << "the X Position is " << xPosition << "," << endl; cout << "the Y Position is " << yPosition << "," << endl; cout << "Direction is " << dirEN << "," << endl; cout << "-----Brilliant-----Cutting-----Lineeeeeeee-----" << endl; } }; int main() { //cout << "hello world" << endl; Robot Alice("Alice",2,4,2); Robot Bob("Bob",4,1,1); Alice.printStatus(); Bob.printStatus(); Alice.moveForward(2); Bob.moveForward(1); Alice.printStatus(); Bob.printStatus(); Alice.rotateCounterClock(); Alice.moveForward(3); Bob.rotateCounterClock(); Bob.moveForward(4); Alice.printStatus(); Bob.printStatus(); return 0; }
输出:
以上是脚本宝典为你收集整理的Cpp小作业-帮助理解Cpp的类,参数,函数全部内容,希望文章能够帮你解决Cpp小作业-帮助理解Cpp的类,参数,函数所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。