我曾经用Visual Studio编写代码,这很容易添加一个类。最近,我转而使用Qt Creator编写纯C ++项目,添加类总是有问题。代码如下:
#include <iostream>
#include "hello.h"
using namespace std;
int main()
{
Hello H;
H.say();
cout << "Hello World!" << endl;
return 0;
}
我创建了一个名为Hello的类并将其包含在main.cpp中,但是当我编译它时,会发生一些错误。
那么如何使用QT创建者添加一个类?提前谢谢!
答案 0 :(得分:8)
使用main.cpp
和Hello
类的非常小的CMake示例项目如下所示:
的CMakeLists.txt:
cmake_minimum_required(VERSION 2.8.11)
project(example)
# Useful CMake options for Qt projects
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
# Search desired Qt packages
find_package(Qt5Core REQUIRED)
# Create a list with all .cpp source files
set( project_sources
main.cpp
hello.cpp
)
# Create executable with all necessary source files
add_executable(${PROJECT_NAME}
${project_sources}
)
qt5_use_modules( ${PROJECT_NAME} Core )
main.cpp中:
#include <iostream>
#include "hello.h"
using namespace std;
int main()
{
Hello H;
H.say();
cout << "Hello World!" << endl;
return 0;
}
Hello.h:
#ifndef HELLO_H
#define HELLO_H
class Hello
{
public:
Hello();
void say();
};
#endif // HELLO_H
HELLO.CPP:
#include <iostream>
#include "Hello.h"
Hello::Hello()
{
}
void Hello::say()
{
std::cout << "Hello from hello class!" << std::endl;
}
答案 1 :(得分:-1)
手动方式:编辑.pro,然后在“SOURCES”和“HEADERS”部分添加.h和.cpp,如下所示:
SOURCES += hello.cpp
HEADERS += hello.h