如何将其从 objective-c 转换为非托管C++

1)property ( nonatomic, assign, getter = isCanceled ) BOOL canceled;
顺便说一句-isCanceled = false;,所以为什么不对`property(nonatomic,assign)BOOL取消进行权衡;

与其他运算符在代码的另一部分中一样:

2)property ( nonatomic, retain ) Im* img;
并且这种构造在c++中只是常量吗?

3)property ( nonatomic, readonly ) Parameter* firstPar;,这在c++中类似于变量const Parameter* firstPar;吗?

以及如何正确翻译第一和第二属性???

最佳答案

我在Objective C方面经验不足,但是据我了解,翻译如下:

// property ( nonatomic, assign, getter = isCanceled ) BOOL canceled
private:
  bool canceled;             // inner backing field
public:
  bool isCanceled() const // getter has a special name
  {
      return canceled;
  }
  void setCanceled(bool newCanceled) // standard setter
  {
      canceled = newCanceled;
  }

对于带有保留的指针属性,最好使用共享指针。但是,外部代码必须遵守其语义。
// property ( nonatomic, retain ) Im* img;
private:
  // we could use manual retain/release with some kind of shared pointers,
  // but an easier way would be to use automatic refcounting
  std::shared_ptr<Im*> img; // shared_ptr because retain
public:
  Im* getImg() // getter
  {
      return img.get();
  }
  void setImg(Im* newImg) // setter
  {
      img.reset(newImg);
  }

第三是最简单的。无需共享指针,因为不涉及retain
// property ( nonatomic, readonly ) Parameter* firstPar;
private:
  Parameter* firstPar;
public:
  Parameter* getFirstPar()
  {
      return firstPar;
  }
  // no setter because readonly

等等

C++没有字段的概念,因此您必须通过手动创建getter和setter来模仿Java。

编辑:
感谢评论中的讨论,我已经通过删除互斥防护来更正了答案。如果有atomic,则将需要它。

使用atomic,您将需要一个附加的互斥量:
// property ( atomic, assign, getter = isCanceled ) BOOL canceled
private:
  bool canceled;             // inner backing field
  std::mutex canceledGuard;  // ensure atomicity
public:
  bool isCanceled() const // getter
  {
      std::lock_guard<std::mutex> lock(canceledGuard);
      return canceled;
  }
  void setCanceled(bool newCanceled) // setter
  {
      std::lock_guard<std::mutex> lock(canceledGuard);
      canceled = newCanceled;
  }

10-05 23:11