【问题标题】:When I use the int keyword the output is always 0当我使用 int 关键字时,输出始终为 0
【发布时间】:2022-09-27 23:30:39
【问题描述】:
#include <iostream> 
#include <string>
using namespace std;                

class ran{
  private:
    int population;
  public:
    void set(int x){
      int population = x;
    }
    int get(){
      return population;
    }    
};
int main() {
  ran linux;
  linux.set(50900);
  cout <<linux.get();
  return 0;
}

在第 7 行中,当我使用 int 关键字将 population 设置为 x 并运行代码时,输​​出将始终为 0,但是当我删除 int 关键字时,它工作正常,有人可以告诉为什么会这样。From where I got the basis of the code

  • 当您输入int 时,您有一个局部变量,请获取一本教科书。
  • int population = x; 除了分配一个局部变量没有任何作用。你的意思是写population = x;吗?
  • int population 创建一个新变量。所以现在你有两个了!
  • 启用编译器警告。你的编译器可能会告诉你这个错误。
  • 顺便说一句,你可以永远不能通过编写随机代码来学习 C++,看看会发生什么。而是尝试首先了解它应该如何工作,也许从这里开始learncpp.com

标签: c++


【解决方案1】:

当您编写int population = x; 时,它会在该函数内创建一个名为population 的新局部变量,并将其值设置为x。类变量population 是一个不受影响的独立变量。

当您编写population = x; 时,它会查找名为population 的变量,在类中找到一个变量,并将类变量population 设置为x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-04
    • 2018-01-14
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多