首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么不使用引用地址指针进行C++编译?

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

Stack Overflow用户
提问于 2011-04-30 06:36:14
回答 2查看 380关注 0票数 1

我是一名计算机科学专业的学生,并参加了我的第一堂C++课程。我很难理解我的代码是怎么回事:

代码语言:javascript
运行
复制
// 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. ,所以我的第一个问题是为什么不编译它?我对我的其他简单程序一点问题都没有。我在OSX4.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::operator<< (std::basic_ostream >& char const*)",引用自:_main in 9-8.o _main in 9-8.o "std::ios_base::Init::Init()",引用自:__static_initialization_and_destruction_0(int,int),在9-8.o中

"std::basic_string,std:size() const",引用于:std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)中的9-8.o "std::basic_string,std::allocator ::operatorunsigned long const",引用自:std::__verify_grouping( const*,未签名),std::basic_string,std::分配器>const&)在9-8.o std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)中9-8.o std::__verify_grouping( const*,unsigned,std::basic_string,std::allocator >const&)在9-8.o "___gxx_personality_v0“中,参考来源: std::__verify_grouping(char const*,unsigned long,std::basic_string::allocator> const&)in 9-8.o ___tcf_0 in 9-8.o _main in 9-8.o(Int)在9-8.o全局构造函数中,在9-8.o "std::ios_base::Init::~Init()“中键为mainin 9-8.ocie,引用为:___tcf_0 in 9-8.o "std::basic_ostream >& std::endl (std::basic_ostream >&)",引用来源:_main in 9-8.o "std::basic_ostream ::operator<<(std::basic_ostream >& (std::basic_ostream>&)“),引用于:_main in 9-8.o "std::basic_ostream ::operator<<(int)",引用于:_main in 9-8.o "std::cout",引用来源:_main in 9-8.o _main in 9-8.o _main in 9-8.ld:符号collect2: ld返回1退出状态:* 9-8错误1

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-30 06:39:16

原因:您没有正确地使用比较操作符。在将其更改为"<“之后,您的代码应该正确工作。

代码语言:javascript
运行
复制
for(count = 0; count << NUM_COINS; count++)
                     ^ should be "<" here
票数 8
EN

Stack Overflow用户

发布于 2011-04-30 06:41:36

除了for循环中的一个问题之外,我没有看到任何问题:

代码语言:javascript
运行
复制
for(count = 0; count << NUM_COINS; count++)
                   //^^

这不是比较。那是左转操作。我相信你不是故意的。

应该是:count < NUM_COINS

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5840064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档