【发布时间】:2011-08-15 22:52:14
【问题描述】:
我是一名计算机科学专业的学生,正在上我的第一堂 C++ 课程。我无法理解我的代码发生了什么:
// This program uses the address of each element in the array.
#include <iostream>
using namespace std;
int main()
{
const int NUM_COINS = 5;
int coins[NUM_COINS] = {5, 1, 25, 5, 10};
int *p1; // Pointer to a double.
int count; // Counter variable.
// Use the pointer to display the values in the array.
cout << "Here are the values in the coins array: \n";
for(count = 0; count << NUM_COINS; count++)
{
// Get the address of an array element
p1 = &coins[count];
// Display the contents of the element
cout << *p1;
}
cout << endl;
return 0;
}
- 所以我的第一个问题是为什么不编译它?我对任何其他简单程序都没有任何问题。我在 OS X 4.2.1 上使用 g++。我必须键入 g++ -o 命令才能编译,如果没有...我收到以下错误:
g++ -c -o 9-8.o 9-8.cpp cc 9-8.o -o 9-8 未定义符号:“std::basic_ostream >& 标准::运算符
(std::basic_ostream >&, 字符 const*)”,引用自: _main 在 9-8.o _main 在 9-8.o "std::ios_base::Init::Init()", 参考自: __static_initialization_and_destruction_0(int, int)in 9-8.o
“std::basic_string, std::allocator >::size() const", 参考自: std::__verify_grouping(char const*, unsigned long, std::basic_string, 9-8.o 中的 std::allocator > const&) “std::basic_string, 标准::分配器 ::operator[](unsigned long) const",引用自: std::__verify_grouping(char const*, unsigned long, std::basic_string, 9-8.o 中的 std::allocator > const&) std::__verify_grouping(char const*, unsigned long, std::basic_string, 9-8.o 中的 std::allocator > const&) std::__verify_grouping(char const*, unsigned long, std::basic_string, 9-8.o 中的 std::allocator > const&) “___gxx_personality_v0”,引用 从: std::__verify_grouping(char const*, unsigned long, std::basic_string, 9-8.o 中的 std::allocator > const&) ___tcf_0 在 9-8.o _main 在 9-8.o unsigned long const& std::min(unsigned long const&, unsigned long const&)in 9-8.o __static_initialization_and_destruction_0(int, int)in 9-8.o 全局构造函数键入 mainin 9-8.o CIE 在 9-8.o "std::ios_base::Init::~Init()", 参考自: ___tcf_0 in 9-8.o "std::basic_ostream >& 标准::endl (std::basic_ostream >&)", 参考自: _main 在 9-8.o "std::basic_ostream ::operator& (*)(std::basic_ostream >&))", 参考自: _main 在 9-8.o "std::basic_ostream ::operator
这引出了我的第二个问题。即使我确实键入了 g++ 命令,它也会编译,但在运行后会输出一个空数组。所以我的问题 #2 是:我的代码正确吗?如何在引用地址语句中正确使用指针?
【问题讨论】:
-
对不起格式,我不明白这个网站的格式
-
@J-e-L-Lo :使用编辑器窗口上的
{}标记来格式化代码。 -
左移运算符代替比较运算符是一个错误,但我仍然不明白为什么这会给你 std::iostream 错误。一旦你解决了这个问题,其余的代码对我来说就可以了。
-
@Sriram:是的,我认为该错误是特定于编译器的。
-
有趣的是,g++ 命令除了显示字符串内容外,程序运行良好。