你从经验中学到的一些C ++相关的成语,误解和困惑是什么? [英] What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?

查看:131
本文介绍了你从经验中学到的一些C ++相关的成语,误解和困惑是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你从经验中学到的一些C ++相关的成语,误解和困惑是什么?

What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?

例如:

class A
{
  public: 
  char s[1024];
  char *p;

  A::A()
  {
    p = s;
  }

  void changeS() const
  {
    p[0] = 'a';
  }

};

即使知道changeS是一个const成员函数,它改变了对象的值。所以一个const成员函数只意味着它将所有的变量作为const,并不意味着它实际上会保持所有成员const。 (为什么成员函数上的const关键字将char * p;作为char * const p;而不是作为const char * p;

Even know changeS is a const member function, it is changing the value of the object. So a const member function only means that it will treat all variables as const, and it does not mean that it will actually keep all members const. (why? the const keyword on the member function treats char *p; as char * const p; And not as const char *p;

推荐答案

我喜欢这个,因为时间我发现它在一些代码:

I've liked this since the time i've discovered it in some code:

assert(condition || !"Something has gone wrong!");

或如果您没有手头的条件,您可以执行

or if you don't have a condition at hand, you can just do

assert(!"Something has gone wrong!");

以下内容属于 @Josh (请参阅评论),它使用逗号运算子

The following is attributed to @Josh (see comments). It uses the comma operator instead:

assert(("Something has gone wrong!", condition));

这篇关于你从经验中学到的一些C ++相关的成语,误解和困惑是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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