2012-07-23 49 views
1

我想要做的事很简单,但我可能有语法错误。acces C++ datamember在objective-c类

我有一个Objective-C接口和Note class参数。 Note.h是一个基本如下所示的C++类:

#include <string> 
using namespace std; 

class Note { 
public: 
    string name; 
    Note(string name){ 
     this->name = name; // ERROR: Cannot find interface declaration for 'Note' 
    } 

}; 

这是我的控制器,它使用的是注释。我改变文件扩展名.mm

@class Note; 
@interface InstrumentGridViewController : UIViewController { 
@public 
    Note* note; 
} 
@property (nonatomic, retain) Note* note; 

这是我如何使用它:

@implementation InstrumentGridViewController 
@synthesize note; 

- (void)buttonPressed:(id)sender { 
    note = Note("fa"); // ERROR: Cannot convert 'Note' to 'Note*' in assignment 
    NSLog(@"naam van de noot is %s", note->name); // ERROR: Cannot find interface declaration for 'Note' 
} 

虽然(我将他们添加上的评论我得到这三个错误右行)

任何想法我怎么做错了?

回答

1

你需要使用new来分配Note对象:

- (void)buttonPressed:(id)sender 
{ 
    if (note != 0) 
     delete note; 
    note = new Note("fa"); 
    NSLog(@"naam van de noot is %s", note->name.c_str()); 
} 

但是似乎有权做的是,在按下按钮的操作方法不...

也不要忘记到delete它在你的对象的dealloc方法:

- (void)dealloc 
{ 
    delete note; 
    [super dealloc]; 
} 

最后你@property在致敬retain是错误的,因为它不是Objective-C对象;改为使用assign,更好的是使其成为readonly

一个更好的方法来初始化大部分对象是使用const引用它们,而不是一个副本:

Note(const string &name) 
{ 
    this->name = name; 
} 
+0

...并且不要忘记删除'buttonPressed中的旧音符:' – 2012-07-23 17:01:40

+0

@NikolaiRuhe是的,对象的一生似乎与我不直观... – trojanfoe 2012-07-23 17:02:24

+0

Where or when我应该分配的对象比? 'buttonPressed'是我第一次使用它,所以我认为我会在那里使用它。 – networkprofile 2012-07-23 17:04:37

1

你注意C++类是无效的。改变其声明是不是:

class Note { 
public: 
    string name; 
    Note(string aName) { 
     name = aName; 
    } 
}; 

也能改变你InstrumentGridViewController

- (void)buttonPressed:(id)sender { 
    note = new Note("fa"); 
    NSLog(@"naam van de noot is %s", note->name); 
} 

- (void)dealloc { 
    delete note; 
    [super dealloc]; // Use this only if not using ARC 
} 
+0

'Note'类声明是如何失效的? – trojanfoe 2012-07-23 17:11:19

+0

实际上,在我的构造函数中使用'this->'也给了''找不到'Note'错误的接口声明,并解决了这个问题。但NSLog不起作用,仍然给我同样的问题。 – networkprofile 2012-07-23 17:15:22

0

Cannot find interface declaration for 'Note'错误是因为在我的Obj-C controller .h file.这很奇怪,因为我有在使用@class工作示例项目@class Note引起它工作正常。

我固定它使用前向声明它们被描述herehere.

// used typedef struct <classname> <classname> 
typedef struct Note Note; 

// instead of 
@class Note 

上面那张在的OBJ-C标题文件的方式。在.mm文件中使用#import "Note.h"语句