在此範圍內未宣告錯誤
如果使用未知物件,則會發生此錯誤。
變數
不編譯:
#include <iostream>
int main(int argc, char *argv[])
{
{
int i = 2;
}
std::cout << i << std::endl; // i is not in the scope of the main function
return 0;
}
固定:
#include <iostream>
int main(int argc, char *argv[])
{
{
int i = 2;
std::cout << i << std::endl;
}
return 0;
}
功能
大多數情況下,如果不包含所需的標頭,則會發生此錯誤(例如,使用
std::cout
而不使用#include <iostream>
)
不編譯:
#include <iostream>
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
void doCompile()
{
std::cout << "No!" << std::endl;
}
固定:
#include <iostream>
void doCompile(); // forward declare the function
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
void doCompile()
{
std::cout << "No!" << std::endl;
}
要麼:
#include <iostream>
void doCompile() // define the function before using it
{
std::cout << "No!" << std::endl;
}
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
注意: 編譯器從上到下解釋程式碼(簡化)。在使用之前必須至少宣告(或定義)所有內容 。