为什么我需要在用户为其赋值之前初始化此变量
Why do I need to initialise this variable before the user assigns a value to it?
我希望用户为 int temp1 和 int temp2 分配一个值。但是,编译器说我需要初始化两个变量之一(temp2)。
为什么它只要求我初始化 temp2 而不是 temp1?当我为 temp2 分配一个值时,程序会忽略用户输入的任何值。
我的代码是否草率,如果是这样,有没有办法解决这个问题?
(我已经包含了整个程序,以防它相关,但是我收到的错误是在inputDetails()函数中。
#include <iostream>
using namespace std;
//Prototype
void inputDetails(int* n1, int* n2);
void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum);
//Functions
int main()
{
int num1;
//num1 pointer
int* n1 = &num1;
int num2;
//num2 pointer
int* n2 = &num2;
//get pNum to point at num1
int* pNum;
pNum = new int;
*pNum = num1;
//pointer to pNum
int** ppNum = &pNum;
//call functions
inputDetails(n1, n2);
outputDetails(num1, num2, pNum, n1, n2, ppNum);
//change pNum to point at num2
delete pNum;
pNum = new int;
*pNum = num2;
//call function again
outputDetails(num1, num2, pNum, n1, n2, ppNum);
delete pNum;
system("PAUSE");
return 0;
}
void inputDetails(int* n1, int* n2)
{
int temp1, temp2;
cout << "Input two numbers" << endl;
cin >> temp1, temp2;
*n1 = temp1;
*n2 = temp2;
}
void outputDetails(int num1, int num2, int* pNum, int* n1, int* n2, int** ppNum)
{
cout << "The value of num1 is: " << num1 << endl;
cout << "The address of num1 is: " << n1 << endl;
cout << "The value of num2 is: " << num2 << endl;
cout << "The address of num2 is: " << n2 << endl;
cout << "The value of pNum is: " << pNum << endl;
cout << "The dereferenced value of pNum is: " << *pNum << endl;
cout << "The address of pNum is: " << ppNum << endl;
}
为什么它只要求我初始化
temp2
而不是temp1
?
以下内容不会执行您认为它的作用(它无意中使用了逗号运算符):
cin >> temp1, temp2;
要从cin
读取两个值,请使用:
cin >> temp1 >> temp2;
相关文章:
- 使用通用值初始化 std::map,不重复
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- C++使用另一个数组和新值初始化数组
- 标准::unordered_map 中的 std::array 的值初始化
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 从 BubbleSort* 类型的右值初始化 'AssortedSorter&' 类型的非常量引用无效"
- 使用运算符"="在C++中用值初始化对象
- 静态分配对象的值初始化
- 是否可以使用右值初始化数据成员?
- C++值初始化矢量迭代器比较
- 使用值初始化访问构造函数?
- 无法使用类型 'const char *' 的左值初始化类型 'char *' 的成员子对象
- 无法取消引用值初始化迭代器
- 是否可以使用函数返回的值初始化数组
- 为什么我总是收到此错误:从类型为"农场动物"的右值初始化类型的非常量引用无效|
- 特征::向量;在函数中使用 Eigen::Matrix3f 的值初始化向量,大于 4 个条目
- 选择用于赋值初始化的转换函数的优先级
- 创建一个可以通过赋值初始化但不可复制的类型
- 为什么赋值初始化在不使用复制构造函数的情况下需要复制构造函数
- 构造函数的赋值初始化