那么,至少有两种低级方法可以确定给定的数字是否是偶数:
1. if (num%2 == 0) { /* even */ }
2. if ((num&1) == 0) { /* even */ }
Run Code Online (Sandbox Code Playgroud)
我认为第二种选择更加优雅和有意义,而这正是我经常使用的选择.但这不仅仅是品味问题; 实际性能可能会有所不同:通常按位操作(例如logial和here)比mod(或div)操作更有效.当然,你可能会争辩说有些编译器无论如何都能优化它,我同意......但有些人不会.
另一点是,对于经验不足的程序员来说,第二个可能有点难以理解.关于这一点,我回答说,如果这些程序员花很短的时间来理解这种语句,它可能只会让每个人受益.
你怎么看?
只有当num无符号整数或具有二进制补码表示的负数时,给定的两个片段才是正确的. - 正如一些评论所说的那样.
看看这里:在下面的代码中,b的类型是什么?
struct A {
A (int i) {}
};
struct B {
B (A a) {}
};
int main () {
int i = 1;
B b(A(i)); // what would be the type of b
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果有人能够彻底向我解释为什么会存在这样的语法,我将不胜感激:)
谢谢.
以下代码应该是自解释的.我有两个关于使用语法的问题(这是必须使用的语法).如果你能为这些提出的问题提供答案,我将永远感激不尽.
template <typename T>
struct A {
template <typename S>
void f (const A<S> &s);
template <typename S>
friend struct A;
// Question 1: why isn't the syntax 'friend struct A<S>' ?
// The semantic would stay, since we would like A<S> (for ANY S) to be friend of every A<T>..
private:
void g () const {}
};
template <typename T>
template <typename S> // Question 2: Why can't the syntax be 'template <typename T, typename S>' ?
void A<T>::f …Run Code Online (Sandbox Code Playgroud)