2012-07-23 50 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"語句