-4

这是代码,如果有什么问题请帮助我。

#include <iostream>

int main() {
    char ch = 'A';
    int num = ch;
    cout << "The ASCII code for " << ch << "is " << num << "\n";
    cout << "Adding 1 to the character code : \n";
    ch = ch + 1;
    num = ch;
    cout << "The ASCII code for " << ch << "is " << num << "\n";
    return (0);
}

我得到像这样的错误

ex1.cpp: In function ‘int main()’:
ex1.cpp:6:5: error: ‘cout’ was not declared in this scope
ex1.cpp:6:5: note: suggested alternative:
/usr/include/c++/4.6/iostream:62:18: note:   ‘std::cout’

各位大侠请指正我的错误。

4

4 回答 4

3

问题是 iostream 标头为您提供了这些对象,但仅在std命名空间下。通过在它们前面加上以下前缀来使用限定名称std::

std::cout << code;

通常建议您不要使用using namespace std因为它会将令牌引入全局命名空间。您最好使用命名空间前缀作为替代方案。

于 2013-03-09T18:00:58.300 回答
3

全局cout对象在std命名空间中定义(与标准库中的所有内容非常相似,只有少数例外)。

因此,您可以完全限定名称(并使用std::cout):

std::cout << "The ASCII code for " << ch << "is " << num << "\n";
// ...

或者引入一个using 声明

using std::cout;
cout << "The ASCII code for " << ch << "is " << num << "\n";
// ...

避免使用的、全局的 using 声明:

using namespace std;

这会将命名空间中定义的所有符号导入std全局命名空间,从而导致名称冲突的高风险。这是一种不好的编程习惯,只能在有限的情况下使用。

于 2013-03-09T18:02:31.497 回答
0

使用std::cout或添加std命名空间。把它放在文件的顶部:

using namespace std;
于 2013-03-09T18:00:30.043 回答
-1

cout是在命名空间中定义的流std。因此,当您使用它时,您要么必须编写,要么在第一次使用 cout 之前std::cout需要全局范围内的一行using std::cout

于 2013-03-09T18:02:45.147 回答