在被建议阅读"Stanley B. Lipman编着的C++ Primer 5"后,我不明白这一点:
第66页."涉及无符号类型的表达式"
unsigned u = 10;
int i = -42;
std::cout << i + i << std::endl; // prints -84
std::cout << u + i << std::endl; // if 32-bit ints, prints 4294967264
Run Code Online (Sandbox Code Playgroud)
他说:
在第二个表达式中,int值-42在添加完成之前转换为unsigned.将负数转换为无符号的行为就像我们尝试将该负值分配给无符号对象一样.如上所述,值"环绕".
但如果我做这样的事情:
unsigned u = 42;
int i = -10;
std::cout << u + i << std::endl; // Why the result is 32?
Run Code Online (Sandbox Code Playgroud)
如您所见-10,未转换为unsigned int.这是否意味着一个比较提倡之前发生signed integer到unsigned integer?
这是一个switch声明的例子.我不知道它为什么这样工作:
int main(){
int number1 = 100, number2 = 200;
switch(number1){
case 100:{
cout << " outer switch number is: " << number1 << endl;
case 200:{ // any value other than 100
cout << "inner switch number is: " << number2 << endl;
}
break;
}
break;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序打印:100然后打印下一个语句case 200.此外,如果200在第二种情况下使用的值以外的任何值,它仍然会被执行.我知道break之后没有了case 100.但是为什么我不会得到编译时错误呢?
为了更清楚,为什么内部案例中的任何其他价值也会成功?例如,
case 70000:
Run Code Online (Sandbox Code Playgroud)我有一个简单的问题:我知道我可以声明const指向某个数据类型的指针或指向常量数据类型的指针,但我只能声明对常量数据类型的引用,而不能对数据类型进行常量引用; 引用已经不变的事实,因为它不能反弹到另一个对象.
所以当我尝试创建一个const ref to someDataType我得到编译时错误.但重要的是与type alias使用typedef或使用时using.例如:
#include <iostream>
int main() {
int i{ 10 };
// int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here.
using rInt = int&; // or typedef int& rInt;
const rInt r2{ i }; // why const is allowed here?
++r2; // this proves that the const is applied to the reference not to the object referred …Run Code Online (Sandbox Code Playgroud) 如果我有一个具有两个成员数据x_并y_声明x_为从初始化y_并y_具有一个值的类,则它x_具有一个Undefined value?或者是什么?
class Empl {
public:
int x_{ y_ };
int y_{ 10 };
};
int main(){
Empl e{};
std::cout << e.x_ << ", " << e.y_ << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我试过例如在MSVC ++ 2105和得到:0和10而在GCC我10和10!
因此,这样做是不确定的行为吗?
出于某些教育原因,我设法通过将引用运算符重载&为已删除的成员函数或private方法来阻止其他人获取我的类对象的地址.但是C++ 11提供了一个新的模板化函数std::addressof,它返回一个对象的地址.所以我也想禁用它,但是我陷入了半解决方案.这是我的代码尝试:
#include "stdafx.h"
#include <memory>
class Foo {
public:
Foo* operator&() = delete; // declared deleted so no one can take my address
friend Foo* addressof(Foo&) = delete; // ok here.
private:
// Foo* operator&() { return nullptr; } // Or I can declare it private which conforms to older versions of C++.
};
int main() {
Foo f{};
// std::cout << &f << std::endl;
// std::cout << addressof(f) << std::endl; // ok …Run Code Online (Sandbox Code Playgroud) 在"C++入门第5版"中,page 228该表Table 4.4. Operator Precedence显示了操作数和操作数的关联性.
令我困惑的是在这个表中说Prefix增量/减量是从右到左的关联,Postfix增量/减量也是从右到左所以有字母"R"表示从右到左.但在www.cppreference.com我看到后缀增量/减量是从左到右的关联.
如果有人通过给出包含复合表达式的示例来澄清事情,那么非常感谢.