我想要做的很简单,但是我可能把语法搞错了。
我有一个带有Note class参数的Objective-C接口。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'
}
};这是我的控制器,使用的是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'
}我得到了这三个错误(我已经在正确的行上添加了它们作为注释)
知道我哪里做错了吗?
发布于 2012-07-24 00:59:24
您需要使用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());
}然而,在按钮按下操作方法中这样做似乎是不正确的……
另外,别忘了在对象的dealloc方法中对其进行delete:
- (void)dealloc
{
delete note;
[super dealloc];
}最后,您的@property属性retain是错误的,因为它不是Objective-C对象;请使用assign,最好还是让它成为readonly。
初始化大多数对象的更好方法是使用对它们的const引用,而不是副本:
Note(const string &name)
{
this->name = name;
}发布于 2012-07-24 01:07:22
您的备注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
}发布于 2012-07-24 03:36:15
Cannot find interface declaration for 'Note'错误是由于我的Obj-C controller .h file.中的@class Note引起的,这很奇怪,因为我有一个使用@class的工作样例项目,它工作得很好。
我使用here和here.的描述方式使用转发声明修复了这个问题
// used typedef struct <classname> <classname>
typedef struct Note Note;
// instead of
@class Note上面的代码放在Obj-C头文件中。#import "Note.h"语句位于.mm文件中
https://stackoverflow.com/questions/11616876
复制相似问题