为什么不应该在C++中使用char和其他C函数?

有人可以就这个问题的答案给我启发吗?在结构中为 char* 分配一个值?

在答案,他们告诉提问者不要混用C和C ++,即使用stringcin如果它的C ++或者
char如果它的C.这让我迷惑,因为我知道那是什么,我们可以用这样的charprintf所以在C ++通过包括适当的库. 如果char因为几个原因我们应该在 C++ 项目中工作怎么办?

答案之一还说typedef struct{...}x;在 C++ 中没有必要,而到目前为止我知道它用于防止重新键入struct x,例如x Name1; x Name2;代替struct x Name1; struct x Name2;. 对于像我这样的初学者来说,这已经足够令人困惑了。

回答

C 和 C++ 是不同的语言,无论它们看起来多么相似以及它们有什么共同的子集。作为不同的语言,它们的方法只能在该语言中使用。当你知道你在做什么时,混合它们是很好的。正如其他答案所述, char 数组比 更难使用std::string,尽管它们有其优点。对于初学者,如果您想学习 C++,std::string与使用相比,学习将为您节省大量调试代码中发生的奇怪事情char*


您不需要的原因typedef struct {} X是 C 和 C++ 是不同语言的主要样本。struct X每次在 C++ 中使用时都不需要重复,无论是否使用typedef. 我什至会说这是有害的,因为它的void foo(struct X*)作用不仅仅是void foo(X*). 此外,struct在 C++ 中相当于class,唯一的区别是默认访问说明符(structhaspublic作为默认值,classhas private)。

  • Also, the C standard library is available in C++. Quite a lot of C code will compile through a C++ compiler and will execute just fine. However, there different conventions and idioms in C and C++. That is why `malloc()` is not good C++ even though you are able to use it. `std::string` is preferred over [raw pointers](https://docs.microsoft.com/en-us/cpp/cpp/raw-pointers?view=msvc-160) because we can avoid explicit memory management. We can lean on the C++ standard library to do the memory management for us. Raw pointers are bad modern C++: use unique pointers or shared pointers.

以上是为什么不应该在C++中使用char和其他C函数?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>