首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问objective-c类中的c++数据成员

访问objective-c类中的c++数据成员
EN

Stack Overflow用户
提问于 2012-07-24 00:48:34
回答 3查看 96关注 0票数 1

我想要做的很简单,但是我可能把语法搞错了。

我有一个带有Note class参数的Objective-C接口。H是一个C++类,基本上看起来像这样:

代码语言:javascript
复制
#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

代码语言:javascript
复制
@class Note;
@interface InstrumentGridViewController : UIViewController {
@public
    Note* note;
}
@property (nonatomic, retain) Note* note;

这就是我使用它的方式:

代码语言:javascript
复制
@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'
}

我得到了这三个错误(我已经在正确的行上添加了它们作为注释)

知道我哪里做错了吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-24 00:59:24

您需要使用new分配Note对象

代码语言:javascript
复制
- (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

代码语言:javascript
复制
- (void)dealloc
{
    delete note;
    [super dealloc];
}

最后,您的@property属性retain是错误的,因为它不是Objective-C对象;请使用assign,最好还是让它成为readonly

初始化大多数对象的更好方法是使用对它们的const引用,而不是副本:

代码语言:javascript
复制
Note(const string &name)
{
    this->name = name;
}
票数 0
EN

Stack Overflow用户

发布于 2012-07-24 01:07:22

您的备注C++类无效。将其声明改为:

代码语言:javascript
复制
class Note {
public:
    string name;
    Note(string aName) {
        name = aName;
    }
};

还要更改您的InstrumentGridViewController

代码语言:javascript
复制
- (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
EN

Stack Overflow用户

发布于 2012-07-24 03:36:15

Cannot find interface declaration for 'Note'错误是由于我的Obj-C controller .h file.中的@class Note引起的,这很奇怪,因为我有一个使用@class的工作样例项目,它工作得很好。

我使用herehere.的描述方式使用转发声明修复了这个问题

代码语言:javascript
复制
// used typedef struct <classname> <classname>
typedef struct Note Note;

// instead of
@class Note

上面的代码放在Obj-C头文件中。#import "Note.h"语句位于.mm文件中

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11616876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档