小编oct*_*pus的帖子

为什么数组的维是其类型的一部分?

在阅读C ++ Primer书籍时,我遇到了这样的说法:“数组中元素的数量是数组类型的一部分。” 因此,我想使用以下代码进行查找:

#include<iostream>

int main()
{
    char Array1[]{'H', 'e', 'l', 'p'};
    char Array2[]{'P', 'l', 'e', 'a', 's', 'e'};

    std::cout<<typeid(Array1).name()<<std::endl;        //prints  A4_c
    std::cout<<typeid(Array2).name()<<std::endl;        //prints  A6_c

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,两个数组上的typeid结果表明它们有所不同。

  • 幕后发生了什么事?
  • 为什么数组必须具有包含其大小的类型?仅仅是因为它的大小不应该改变吗?
  • 这将如何影响比较数组?

只是希望能够深刻理解这个概念。

c++ arrays c++11

10
推荐指数
2
解决办法
571
查看次数

在 C++ 中初始化的结果是什么?

初始化的返回值是什么?例如:在下面的代码中;

#include<iostream>

int main()
{
    int age = 30;          //does this statement return (thus; yield) anything?

    while(int i = 0){      //a similar statement (expression) used here in this condition
        std::cout<<"OK";   
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • 语句int age = 27;返回什么?
  • 当存在初始化时,通常的赋值运算符的含义是否适用,其中返回赋值运算符的左操作数?

我想知道这一点的原因是,当我们查看上面的条件语句时,我们看到用作条件的变量的类似初始化。我知道返回的任何值都会转换为 bool 类型。

注意:我不想在 while 语句的条件下将 i 与 0 进行比较。

c++ initialization

6
推荐指数
1
解决办法
95
查看次数

C++ 逗号运算符的优先级

嗨,我对以下代码有些困惑:

int main()
{
    int sum = 0, val = 1;
    while(val <= 10)
        sum += val, ++val;     //source of problem

    cout<<"Sum of 1 to 10 inclusive is " << sum << endl;
    //
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我目前正在学习运算符优先级。知道逗号运算符在 C++ 运算符中的优先级最低,我希望 while 循环中的语句按以下顺序计算:

++val; //so that val is incremented to 2 the first time the code in the while loop is evaluated
sum += val; //so that the incremented value of val is added to the sum variable 
Run Code Online (Sandbox Code Playgroud)

但代码按此顺序评估:

sum += …
Run Code Online (Sandbox Code Playgroud)

c++ operator-precedence comma-operator

5
推荐指数
1
解决办法
128
查看次数

C++ 箭头运算符 (-&gt;) 是否在所有情况下都返回左值?

根据 C++ Primer 一书,“箭头运算符需要一个指针操作数并产生一个左值”。总是这样吗?例如:

#include<iostream>
#include<string>

using std::string; using std::vector;

int main()
{
     vector<string> temp {"aaa", "bbb", "ccc"};
     vector<string>::iterator iter_str = temp.begin();
     bool result = iter_str->empty();  //the result of iter_str->empty() is not an lvalue right?

     return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • 当我们以表达式 iter_str->empty() 为例时,它不可能是赋值运算符的左操作数,对吧?
  • 如果箭头运算符返回一个左值,它不是一直都必须返回吗?或者这个规则有例外吗?

c++ c++11

1
推荐指数
1
解决办法
262
查看次数