[英]Programming error in C++
我最近開始學習C ++,但我遇到了一個問題。 下面給出的程序沒有給出我想要的結果,因為我只在結果中看到'Hi'而不是在void函數中寫的是什么。 請告訴我發生這種情況的原因以及解決方案。
我正在使用Xcode 6.3.1,我選擇了C ++語言。
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
void ABC ();
return 0;
}
您正在重新聲明main()
的void ABC()
函數。 只需撥打ABC();
沒有void
。
您可以查看有關在另一個范圍內聲明函數的此問題 。
在你的代碼中你的函數調用是錯誤的。
調用函數時,無需添加返回類型:
#include
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC ();
return 0;
}
你需要調用你的方法而不是在main中聲明它
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
編輯1:自從你開始學習C ++以來,我推薦以下建議,以確保你的代碼更清晰。 請注意,這些不是任何規則,而是更多的最佳實踐和編碼風格。
這是代碼的第2版,包含3種不同方法和調用的示例:
#include <iostream>
using namespace std;
int sum;
string MethodReturningString()
{
return "Hey there i am the result of a method call !";
}
int MethodReturningInt()
{
return 5;
}
void CalculateSum(int x,int y)
{
sum=x+y;
}
int main()
{
cout << MethodReturningString() << endl;
cout << MethodReturningInt() << endl;
cout << "Calculating sum:" ;
CalculateSum(5,4);
cout << sum << endl;
return 0;
}
快樂的編碼
在C ++中,與幾乎任何其他語言一樣,在調用函數時不指定返回類型。 所以改變讀取的行:
void ABC ();
至:
ABC();
嘗試這個:
#include <iostream>
using namespace std;
void ABC () {
cout << "Hey there ! \n";
}
int main () {
cout << "Hi \n";
ABC();
return 0;
}
您應該通過聲明其名稱並添加括號來調用函數。
而不是使用void ABC()來調用main()中的函數ABC(),使用以下代碼:
#include
void ABC ()
{
cout << "Hey there ! \n";
}
int main ()
{
cout << "Hi \n";
ABC ();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.