I want to call c++ class in my ViewController. So I create a class like this: 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
Hello.mm
#import "Hello.h"
@implementation Hello
-(void)sayHellooooo{
hello = new NewHello();
hello->say_hello();
}
@end
ViewController.h
#import <UIKit/UIKit.h>
//#include "Hello.h"
@class Hello;
@interface ViewController : UIViewController{
}
@end
ViewController.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
It works fine in the project:http://files.cnblogs.com/cpcpc/Objective-C%E8%B0%83%E7%94%A8C.rar
But when I copy the code to my project,it appears "Receiver type for instance messages is a forward declaration" error.
If I change "@class Hello;" to #import "Hello.h",it appears "Unkwon type class,did you mean Class" error in "class NewHello".
I use xcode 4.6.Can anybody help me?Thank you!
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.
The problem is (as you've stated) file type for ViewController.m is Obj-C and Hello.h is a Obj-C++ file. The solution is to add
#import "Hello.h"
to your ViewController.m file and change the file type of ViewController.m to Obj-C++ (from the right panel)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With