C++生成标准构造函数
我经常发现自己编写非常简单的类而不是 C 风格的结构。它们通常看起来像这样:
class A
{
public:
type mA;
type mB;
...
A(type mA,type mB,...) : mA(mA),mB(mB),... {}
}
这是一种明智的做事方式吗?如果是,我想知道是否有任何第三方插件或任何方便的快捷方式来自动构造构造函数的文本(例如,采用突出显示或现有的成员定义,用逗号替换分号,将所有内容移动到同一行, ...)?谢谢
I often find myself writing very simple classes instead of C-style structs. They typically look like this:
class A
{
public:
type mA;
type mB;
...
A(type mA,type mB,...) : mA(mA),mB(mB),... {}
}
Is that a sensible way of doing things? If yes, I was wondering whether there was any third party plugin out there or any handy short cut to automatically construct the text for the constructor (e.g. take the highlighted or existent member definitions, replace semicolons with commas, move everything on the same line, ...)? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说这是一种明智的做法,尽管面向对象的狂热分子可能会评论您缺乏封装。
我知道 Visual Studio 内置了代码片段,可以完成您正在寻找的一半工作,但这取决于您的 IDE
I'd say it was a sensible way of doing it although OO fanatics might comment on the lack of encapsulation you have.
I know Visual Studio has code snippets built in which do half the job you are looking for but it depends on your IDE
是的,只需使用普通聚合:
用法:
聚合没有自定义构造函数、析构函数和赋值运算符,并且它允许进行大量优化。例如,使用大括号语法进行聚合初始化通常会就地构造成员,甚至不需要副本。此外,您还可以获得编译器为您定义的最佳复制和移动构造函数以及赋值运算符。
Yes, just use plain aggregates:
Usage:
An aggregate has no custom constructors, destructor and assignment operator, and it allows for plenty of optimisations. Aggregate initialization with the brace syntax for example usually constructs the members in place without even a copy. Also you get the best possible copy and move constructors and assignment operators defined for you by the compiler.
编辑:以前的版本是c99,而不是c++。现在是 C++
我认为你可以使用 {} 初始化而不是编写构造函数。或者是c++0x中的? c99?我不知道。但它看起来像:
EDIT: previous version was c99, not c++. now it is c++
i think you can use {} initialization instead of writing constructor. or is it in c++0x? c99? i am not sure. but it looks like: