gpt4 book ai didi

c++ - 为什么不使用引用地址指针对 C++ 进行编译?

转载 作者:行者123 更新时间:2023-11-30 00:58:41 26 4
gpt4 key购买 nike

我是一名计算机科学专业的学生,​​正在上我的第一门 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;
}
  1. 所以我的第一个问题是为什么不编译它?我的任何其他简单程序都没有任何问题。我在 OS X 4.2.1 上使用 g++。我必须键入 g++ -o 命令才能编译,如果没有...我会收到以下错误:

g++ -c -o 9-8.o 9-8.cpp cc 9-8.o -o 9-8 Undefined symbols: "std::basic_ostream >& std::operator<<

(std::basic_ostream >&, char const*)", referenced from: _main in 9-8.o _main in 9-8.o "std::ios_base::Init::Init()", referenced from: __static_initialization_and_destruction_0(int, int)in 9-8.o
"std::basic_string, std::allocator >::size() const", referenced from: std::__verify_grouping(char const*, unsigned long, std::basic_string, std::allocator > const&)in 9-8.o "std::basic_string, std::allocator ::operator[](unsigned long) const", referenced from: std::__verify_grouping(char const*, unsigned long, std::basic_string, std::allocator > const&)in 9-8.o std::__verify_grouping(char const*, unsigned long, std::basic_string, std::allocator > const&)in 9-8.o std::__verify_grouping(char const*, unsigned long, std::basic_string, std::allocator > const&)in 9-8.o "___gxx_personality_v0", referenced from: std::__verify_grouping(char const*, unsigned long, std::basic_string, std::allocator > const&)in 9-8.o ___tcf_0 in 9-8.o _main in 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 global constructors keyed to mainin 9-8.o CIE in 9-8.o "std::ios_base::Init::~Init()", referenced from: ___tcf_0 in 9-8.o "std::basic_ostream >& std::endl (std::basic_ostream >&)", referenced from: _main in 9-8.o "std::basic_ostream ::operator<<(std::basic_ostream >& (*)(std::basic_ostream >&))", referenced from: _main in 9-8.o "std::basic_ostream ::operator<<(int)", referenced from: _main in 9-8.o "std::cout", referenced from: _main in 9-8.o _main in 9-8.o _main in 9-8.o ld: symbol(s) not found collect2: ld returned 1 exit status make: *** [9-8] Error 1

这引出了我的第二个问题。即使我确实键入了 g++ 命令,它也会编译,但在运行后会输出一个空数组。所以我的问题 #2 是:我的代码正确吗?如何正确使用带有引用地址语句的指针?

最佳答案

原因:您没有正确使用比较运算符。将其更改为“<”后,您的代码应该可以正常工作。

for(count = 0; count << NUM_COINS; count++)
^ should be "<" here

关于c++ - 为什么不使用引用地址指针对 C++ 进行编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5840064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com