为什么允许我这样做,为什么没有歧义抱怨,为什么选择类的方法在另一个之前?
class EX
{
public:
//...
void operator+(const EX& ref)
{
cout << "A";
}
};
void operator+(const EX& ref1, const EX& ref2)
{
cout << "B" << endl;
}
int main()
{
EX obj1{20};
EX obj2{30};
cout << "obj1 + obj2 = " << obj1 + obj2 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我期待全局函数operator+被称为"B"打印在屏幕上,而不是"A"被打印出来。
我不明白这里发生了什么。一定有一些与“冲洗”术语有关的东西,但我想要一个解释。
int arr[4] {3,8,1,6};
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<endl;
cout<<&arr[0]<<endl;
cout<<&arr[1]<<'\n';
cout<<&arr[2]<<endl;
cout<<&arr[3]<<endl;
cout<<&arr[0]<<endl;
int *j = &arr[0];
cout << *j << *(++j) << *(++j) << *(++j); // HERE IS THE PROBLEM
Run Code Online (Sandbox Code Playgroud)
为什么最后一条cout指令倾向于输出相反的数字?在我看来,我喜欢回溯,但我不确定。
我期待3816作为输出,而不是我得到6618.
我不明白为什么char *ptr = new char[7]不截断大于7个字符的数据输入。也是为什么fourr char c[7]允许我输入超过6个字符的信息(但将其字面值超过6个字符的属性赋予错误)。
对我来说,使用malloc函数执行此操作似乎有点困难,这就是为什么我不想使用它。我暂时不希望使用它。
char qs[7] = "1234567"; //error too many
char qs2[7];
cin >> qs2; //input 123456789
cout << qs2; //out same as input, expecting 123456
char *qs3 = new char[7];
cin >> qs3; //input 123456789
cout << qs3; //out same as input, expecting 123456
Run Code Online (Sandbox Code Playgroud) 我画这个是为了更好地理解。在 PC 的内存中有连续的内存区域,长度为 1 个字节(绿色区域)。它们可以分组以表示更大的数据(如int我们的示例中的an )。
我想添加到这张图片中的是,绿色方块是连续的地址,如0x000000后跟0x000001等。然后地址从arr四跳,0x000000下一个将是0x000004(因为int在这方面是4bytes)。
代码_1:
int arr[4] = {1,2,3,4};
int *p = arr;
cout << p << endl;
cout << ++p << endl;
cout << ++p << endl;
cout << ++p << endl;
Run Code Online (Sandbox Code Playgroud)
输出_1:
0x69fedc
0x69fee0
0x69fee4
0x69fee8
Run Code Online (Sandbox Code Playgroud)
代码_2:
char arrr[5] = {'1','2','3','4', '\n'};
char *ptr = arrr;
cout << &ptr << endl;
cout << &(++ptr) << endl; …Run Code Online (Sandbox Code Playgroud) 我正在尝试将数组的内容复制到自身内部,但带有偏移量(或从偏移量)。例如:
int main(void) {
char a[4] = { 'a', 'b' , 'c', 'd' }, b[4], c[4];
memcpy(b, a, 4);
memcpy(c, b, 4);
memcpy(b, b + 1, 3);
memcpy(c + 1, c, 3);
for(unsigned i = 0; i < 4; i++)
printf("%c", b[i]);
printf("\n");
for(unsigned i = 0; i < 4; i++)
printf("%c", c[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出以下输出:
bcdd
aaaa
Run Code Online (Sandbox Code Playgroud)
我期待
bcdd
aabc
Run Code Online (Sandbox Code Playgroud)
第一个memcpy它有效,但第二个在我看来它不是不一致的,所以我做错了。
我不明白我做错了什么。为什么会失败。另外,如果我尝试做同样的事情,但对于例如结构数组,这仍然会发生吗?
从cppreference,可以说模运算符的原型T T::operator%(const T2 &b) const;来自内部类定义和T operator%(const T &a, const T2 &b);外部类定义。我不知道这里是否是我需要寻找问题答案的地方。
我从这个例子中提出的问题:
int i = 2;
float f = 4.4;
cout << f % float(i); // ERROR
Run Code Online (Sandbox Code Playgroud)
所以:
int?如果是,它在 cppreference 中写在哪里?)f变量转换int为转换吗?收到的错误是invalid operands of types 'float' and 'float' to binary 'operator%'。我期望是类型int和的无效操作数float。