[英]References, Logical Operators, and Loop Condition
我在了解自己在代碼中做錯了什么時遇到了問題。 我想做的是為三元運算符和一個do-while循環寫一個條件,以識別我的變量之一是否大於1。好吧,這給了我一個我不知道如何解決的錯誤。 最讓我困惑的是我不久將舉一個例子。 這是我的整體代碼。 請記住,我是一個初學者,所以有些事情會讓您畏縮或有所改進。
#include <iostream>
using namespace std;
void getInfo(int&, int&, double&);
int main() {
int ordered, stock;
double charges = 10.00;
getInfo(ordered, stock, charges);
system("pause");
return 0;
}
void getInfo(int& ordered, int& stock, double& charges) {
do {
printf("Enter the amount of spools ordered, in stock, and handling charges: ");
scanf_s("%i %i %lf", &ordered, &stock, &charges);
printf((&ordered > 1 && &stock > 0 && &charges > 0) ? "All added!\n"
: "You messed one up. AGAIN!\n");
} while (&ordered > 1 && &stock > 0 && &charges > 0);
}
現在,我得到的錯誤特別是在三元和while條件中。 這給了我一個錯誤,在>
兩者都訂購后。 現在,如果我將其設置為ordered
而不是&ordered
,那么錯誤就會消失。 但是,我從不會對&stock
或&charges
犯錯。 我不知道為什么它的治療&ordered
方式不同。 當我摘下&
,它也不能正確檢查ordered
,原因是我不確定。
謝謝任何願意幫助的人!
...(&ordered > 1 && &stock > 0 && &charges > 0) ? "All added!\n"
在這里,“&ordered”表示“ ordered
變量的地址。您顯然不是在嘗試比較ordered
的地址,而是要對ordered
本身進行比較。這應該是
...(ordered > 1 && stock > 0 && charges > 0) ? "All added!\n"
同樣,您的while()語句也存在問題。
在C ++中,“&”表示兩件事。 在聲明中,它用於聲明引用。 在表達式中,它是運算符的“地址”。
聲明引用后,例如:
int &whatever;
隨后,僅使用whatever
引用對象本身的引用。
: "You messed one up. AGAIN!\n");
&
運算符根據您放置的位置執行不同的操作。 如果它在類型聲明中(例如int& foo
),則意味着該類型是引用 。 但是,如果&
在表達式中用作一元運算符,它將成為Address-of運算符,並返回指向其使用對象的指針。 因此,例如int* bar = &spam
(假設spam
是整數)會在指針欄中分配一個指向垃圾郵件的指針。
請注意,引用類型的行為與真實類型相同。 用一段代碼也許可以更好地說明這一點:
#include <iostream>
int main() {
int foo = 12;
int& bar = foo; // a reference expects a variable of the same type in the initializer
bar = 24; // Once the reference has been made the variable behaves indentically to the
// to the variable it's a reference to.
std::cout << foo << std::endl; // outputs 24
// if you use the & operator on a reference you get the address the variable it is a
// reference to.
std::cout << &bar << ' ' << &foo << std::endl; // Outputs two equal addresses.
}
C ++中還有&
的第三種含義。 作為按位和運算符。 foo & bar
將導致按位和可變的foo
和bar
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.