我试图在我的Mac应用程序上运行本机对象代码。
我的代码如下:
MainWindow.h:
#ifdef Q_OS_MAC
#include <Carbon/Carbon.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <mach/mach_port.h>
#include <mach/mach_interface.h>
#include <mach/mach_init.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
#endif
MainWindow.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(receiveSleepNote:)
name: NSWorkspaceWillSleepNotification object: NULL];
#endif
}
#ifdef Q_OS_MAC
- (void) receiveSleepNote: (NSNotification*) note
{
NSLog(@"receiveSleepNote: %@", [note name]);
}
#endif
但是我得到的错误似乎是QT无法理解代码结构:
application.cpp:错误:预期的外部声明 - (void)receiveSleepNote:(NSNotification *)note ^
答案 0 :(得分:3)
为了使用C ++编译objective-c,您需要在.m或.mm文件中使用objective-c代码。
随后的标题可以包含可以从C ++调用的函数,这些函数的主体可以包含objective-c代码。
所以,比方说,我们想调用一个函数来弹出一个OSX通知。从标题开始: -
#ifndef __MyNotification_h_
#define __MyNotification_h_
#include <QString>
class MyNotification
{
public:
static void Display(const QString& title, const QString& text);
};
#endif
正如您所看到的,这是一个可以从C ++调用的标头中的常规函数。这是实施: -
#include "mynotification.h"
#import <Foundation/NSUserNotification.h>
#import <Foundation/NSString.h>
void MyNotification::Display(const QString& title, const QString& text)
{
NSString* titleStr = [[NSString alloc] initWithUTF8String:title.toUtf8().data()];
NSString* textStr = [[NSString alloc] initWithUTF8String:text.toUtf8().data()];
NSUserNotification* userNotification = [[[NSUserNotification alloc] init] autorelease];
userNotification.title = titleStr;
userNotification.informativeText = textStr;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}
该实现包含objective-c,由于其.mm文件扩展名,编译器将正确处理此问题。
请注意,在您在问题中提供的示例中,您需要考虑代码正在执行的操作;特别是当使用' self '时,我希望它需要引用Objective-C类,而不是C ++类。