![](/img/trans.png)
[英]C++ code to create dynamic array using new works in main, but doesn't work as a separate function
[英]C++ function in main doesn't work
為什么此代碼不打印字母a?
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
void a();
return 0;
}
您不小心在main()
聲明了一個函數,而不是對其進行了調用。
int main ()
{
void a(); // <-- DECLARES a function, does not call it
return 0;
}
解決方法是:
int main ()
{
a();
return 0;
}
另請注意,您可能需要換行符:
void a()
{
std::cout<<"a\n";
}
或者,如果您喜歡鍵入,則可以使用std::endl
。
您兩次聲明函數:
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
void a(); // this is a declaration
return 0;
}
改為這樣做:
int main ()
{
a(); // this is a function call, which will execute your function
return 0;
}
好的qwertyu uytrewq,每個人一開始都有這類問題,主要的是不要猶豫。
代碼中的主要錯誤是,您在聲明函數但未調用它。 功能分為三個階段。
聲明即
無效a();
定義即
無效a(){std :: cout <<“ a”; }
調用函數
一種();
現在,程序中的主要錯誤屬於第三階段(調用函數),您提到的函數類型也稱為Deceleration,因此正確的代碼如下。
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
a();
return 0;
}
在您的主要職能中:
int main()
{
// Don't add Void
a();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.