C++ 尝试将多个类与makefile的构造函数一起使用时出错
我正在尝试使用makefiles,但目前还不太适合我。实验很简单:一个main.cpp创建一个机器人,它有一个函数sayHello(),将“robot says hello”输出到终端。这是我文件中的代码 robot.h:C++ 尝试将多个类与makefile的构造函数一起使用时出错,c++,class,makefile,constructor,C++,Class,Makefile,Constructor,我正在尝试使用makefiles,但目前还不太适合我。实验很简单:一个main.cpp创建一个机器人,它有一个函数sayHello(),将“robot says hello”输出到终端。这是我文件中的代码 robot.h: #include <stdio.h> class Robot(){ public: Robot(); public: void sayHello(); }; main.cpp
#include <stdio.h>
class Robot(){
public:
Robot();
public:
void sayHello();
};
main.cpp
#include <stdio.h>
#include "robot.h"
Robot robocop();
int main(void)
{
printf("hello world \r\n");
robocop.sayHello();
return 0;
}
#include "robot.h"
Robot robocop;
int main(void)
{
robocop.sayHello();
return 0;
}
#包括
#包括“robot.h”
机器人机器人;
内部主(空)
{
printf(“hello world\r\n”);
机器人战警:你好;
返回0;
}
错误如下:
robot.h:2:13:错误:在“')标记之前应为非限定id
类机器人(){
^
main.cpp:在函数“int main()”中:
main.cpp:9:10:错误:请求“robocop”中的成员“sayHello”,该成员属于非类类型“Robot()”
机器人战警:你好
我尝试这个太久了,可能需要一些帮助。谢谢!这与makefile无关
robot.cpp
中的类方法定义是错误的。如前所述,sayHello()
方法奇怪地被推到了类的构造函数中。这是不正确的。每个类方法,包括构造函数,都必须单独定义:
#include "robot.h"
Robot::Robot()
{
}
void Robot::sayHello()
{
printf("Robot says hello \r\n");
}
我已经这样做了: 机器人
#include <stdio.h>
class Robot{
public:
Robot();
public:
void sayHello();
};
main.cpp
#include <stdio.h>
#include "robot.h"
Robot robocop();
int main(void)
{
printf("hello world \r\n");
robocop.sayHello();
return 0;
}
#include "robot.h"
Robot robocop;
int main(void)
{
robocop.sayHello();
return 0;
}
感谢您的帮助!Main:
int main()
{
Robot robocop;
printf("hello world \r\n");
robocop.sayHello();
system("pause>nul");
return 0;
}
注意:在使用system()时要小心。我在本例中使用了它,因为它是最快的,但我建议以后使用其他东西;不过应该可以这样做
标题:
class Robot {
public:
Robot();
void sayHello();
};
Robot.cpp:
Robot::Robot()
{
return;
}
void Robot::sayHello() {
printf("Robot says hello \r\n");
}
正如上面所说的,你写得不正确。我建议看一些关于C++基础的教程。