【问题标题】:Using static_cast over compound operators在复合运算符上使用 static_cast
【发布时间】:2019-12-04 20:32:49
【问题描述】:

我是 C++ 编程的初学者...我在练习,遇到了这个问题...这里我尝试在复合运算符上使用 static_cast...我实际上是在尝试将两个整数相除得到双倍的答案...这是代码:

#include <iostream>
using namespace std;
int main() {
    int g {0}, h {0};
    cout << "Enter g and h: " << endl;
    cin >> g >> h;
    static_cast<double>(g) /= (h);
    cout << "g: " << g << endl;
    return 0;
}

现在我知道我可以将 int 更改为 double...或执行以下操作:

i = g/h;
cout << static_cast<double>(i) << endl;

但是让我们来挑战一下……如果我们真的需要输入整数(不是双精度数)怎么办?

这是我得到的错误:

error: lvalue required as left operand of assignment

示例:通过强制转换更改数据类型

#include <iostream>
using namespace std;

int main()
{
    int total {0};
    int num1 {0}, num2 {0}, num3{0};
    const int count {3};

    cout << "Enter 3 integers: ";
    cin >> num1 >> num2 >> num3;

    total = num1 + num2 + num3;
    double average {0.0};
    //This is where it confuses almost everyone. Imagine total is equal to 50, so average is equal to 16.66.
    //But the problem is that total is an integer so you will only get 16 as answer.
    //The solution is to convert it by casting.
    average = static_cast<double>(total) / count;
    //average = (double)total/count;      //Old-Style code

    cout << "The 3 numbers are: " << num1 << ", " << num2 << ", " << num3 << endl;
    cout << "The sum of the numbers are: " << total << endl;
    cout << "The average of the numbers is: " << average << endl;

    return 0;
}

【问题讨论】:

  • 我不清楚你想在这里做什么。您是否正在尝试将 g 从整数变量转换为双精度变量?
  • 是的..这就是我想要做的
  • 这是不可能的。 g 被声明为 int。它永远是int
  • 变量声明后不能改变类型。
  • 我不确定,但我已经看到他们通过强制转换更改数据类型的示例......让我通过编辑将其实际发布到我的问题中

标签: c++ c++17


【解决方案1】:

我想你误解了static_cast的功能。

static_cast 将(如果可能)将一个值转换为另一种类型,并为您提供新类型的结果右值1rvalue 不是您可以分配给2 的东西(与您在错误消息中看到的左值不同)。

在 C++ 中,变量的类型在声明期间只给出一次且仅一次。对于该变量的整个生命周期,它将是它声明的类型(注意这与 Python 或 JavaScript 等弱类型语言不同)。


在回复您的示例时,请注意没有变量正在改变它们的类型。

average = static_cast<double>(total) / count;

average 被声明为double,它仍然是double。这里的神奇之处在于您将total 转换为double。所以static_cast&lt;double&gt;(total) 给你一个double,其值与整数total 等效(但这不再是total!它现在是一个临时未命名的double)。然后将未命名的double 除以count,并将结果分配给average


1.除非要转换的类型是引用类型。 (感谢布赖恩!)
2.对于本机类型。 “除非您明确禁止,否则可以分配任何类类型右值。” (谢谢内森!)

【讨论】:

  • 右值不是你可以分配给的东西 这仅适用于内置类型。除非您明确禁止,否则任何类类型的右值都可以分配给它。
  • 请注意,如果要转换的类型是引用类型,static_cast 可以产生左值。
  • 是的...我想你是对的...也许唯一的解决方案是将 int 更改为 double 或 float...
  • @David 我已编辑以尝试解决您的示例。这有意义吗?
  • 好的..谢谢大家,谢谢scohe001...祝大家好运:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
  • 2016-10-01
相关资源
最近更新 更多