运营商“重载”相当于在C / Objective-C中的#define [英] Operator 'overloading' equivalent with #define in C/Objective-C

查看:174
本文介绍了运营商“重载”相当于在C / Objective-C中的#define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  操作员用C 超载​​

如果我有一个结构:

typedef struct myStruct {
    ...
} myStruct;

myStruct myStructAdd(myStruct a, myStruct b);

我需要的东西是这样的:

I need something like this:

#define myStruct a + myStruct b myStructAdd(a, b)
// NOTE this code does NOT WORK. This is what the question is asking.

为了使这个语法有效的:

To make this syntax valid:

myStruct a;
myStruct b;
myStruct c = a + b;

有没有办法使用的#define 来做到这一点?

编辑:

我不要求对替代品的+语法。什么我问的是,如果和preprocessor如何,可以用来改写的加语法上编译标准C的语法。

I'm not asking for alternatives to the + syntax. What I'm asking is if, and how, the preprocessor can be used to rewrite the plus syntax to standard C syntax on compile.

即。像的#define MYSTRUCT A + MYSTRUCT b myStructAdd(A,B)果然 myStructA + myStructB myStructAdd(myStructA,myStructB)上编译。

推荐答案

运算符重载根本不是C或Objective-C的一个特点。 C ++允许你定义为运营商和自定义类型的任意行为。在Objective-C,如果两个对象可以被加在一起,则通常有一种方法是:

Operator overloading simply isn't a feature of C or Objective-C. C++ allows you to define arbitrary behaviour for operators and custom types. In Objective-C, if two objects can be added together, then usually there is a method for that:

Foo *result = [foo1 fooByAddingFoo:foo2];

或者,如果类是可变的:

Or, if the class is mutable:

Foo *foo1 = [Foo fooWithBar:bar];

[foo1 addFoo:foo2];

如果操作符重载是一个必须具备的功能,使用C ++来代替,或者使用的Objective-C ++(但请记住,C ++类和Objective-C的对象是完全从根本上有所不同)。

If operator overloading is a must-have feature, use C++ instead, or use Objective-C++ (but keep in mind that C++ classes and Objective-C objects are totally and fundamentally different).

的C proprocessor在概念上非常简单,而且它知道非常,非常小的关于C的语法和什么都没有关于C的类型。如果你想使用preprocessor超负荷运营商的话,那就必须学会在你的code使用的每一个类型(包括自定义类型),它必须以确定哪个函数执行静态类型检查调用,这是东西,是的办法出preprocessor的范围。

The C proprocessor is conceptually very simple, and it knows very, very little about C's syntax, and nothing at all about C's types. If you wanted to overload an operator using the preprocessor, then it would have to learn every type (including custom types) used in your code, and it would have to perform static type checking in order to determine which function to invoke, and this is something that is way out of the scope of the preprocessor.

这是一个有趣的想法,但它根本不可能的。

It's an interesting idea, but it's simply not possible.

这篇关于运营商“重载”相当于在C / Objective-C中的#define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆