12

我想在我的 ViewController 中调用 c++ 类。所以我创建了一个这样的类:Hello.h

#import <Foundation/Foundation.h>

@interface Hello : NSObject{
    class NewHello{
    private:int greeting_text;
    public:
        NewHello(){
            greeting_text=5;
        }
        void say_hello(){
            printf("Greeting_Text = %d",greeting_text);
        }
    };   
    NewHello *hello;
}
-(void)sayHellooooo;
@end

你好.mm

#import "Hello.h"
@implementation Hello
-(void)sayHellooooo{
    hello = new NewHello();
    hello->say_hello();
}
@end

视图控制器.h

#import <UIKit/UIKit.h>
//#include "Hello.h"
@class Hello;

@interface ViewController : UIViewController{
}
@end

视图控制器.m

#import "ViewController.h"

@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
        NSLog(@"dddddddd");
    Hello *aa = [[Hello alloc]init];
    [aa sayHellooooo];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end

在项目中运行良好:http: //files.cnblogs.com/cpcpc/Objective-C%E8%B0%83%E7%94%A8C.rar

但是当我将代码复制到我的项目时,会出现“接收器类型例如消息是前向声明”错误。

如果我更改“@class Hello;” 到#import "Hello.h",在"class NewHello"中出现"Unkwon type class,did you mean Class"错误。

我使用 xcode 4.6。有人可以帮助我吗?谢谢!

4

1 回答 1

24

问题是(如您所说) ViewController.m 的文件类型是 Obj-C 而 Hello.h 是 Obj-C++ 文件。解决方案是添加

#import "Hello.h" 

to your ViewController.m file and change the file type of ViewController.m to Obj-C++ (from the right panel)

于 2013-03-30T22:16:49.730 回答