我的背景是使用更多托管语言(C#,python),但是我对C / C ++越来越有经验。我熟悉为什么通过引用(。)选择和通过指针操作(->)选择不同。在我遇到的所有情况下,如果使用不正确的代码,都会导致编译错误。如果是这样,他们为什么不将其变成一个运算符?是否存在在同一对象上使用其中任何一个都会导致不同,有意义和有用的结果的情况?
这个问题的答案是:用c ++调用函数的正确方法吗?
在C ++中,您可以重载->
-operator,几乎在所有智能指针实现中都使用-operator。但是,其中一些也有自己的方法,即发布参考。
struct test {
int x;
};
std::shared_ptr<int> ptr(new test);
// Write to member x of the allocated object
ptr->x = 3;
// Reset the shared pointer to point to a different object.
// If there are no further shared_ptrs pointing to the previously allocated one,
// it is deleted.
ptr.reset(new test)
另外,对于编译器来说,解析操作符会非常麻烦,.
例如多级指针(即)test*** ptr
。随着你的逻辑,ptr.x
,(*ptr).x
,(**ptr).x
并且(***ptr).x
都将是相同的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句