Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2508575
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-11-18 10:35:44

    建立一个对象数组,内放5个学生的数据(学号,成绩),用指针指向数组首元素,输出第1,3,5个学生的数据。
    如果学习过C语言的话,应该都差不多。定义一个指针,指向首元素,然后通过移动指针,使指针指向下一个元素。代码如下:

#include <iostream>
using namespace std;

class Student
{
    public:
    Student(int = 0,int = 0);
    void display();
    
    private:
    int no;
    int score;
};

Student::Student(int no,int score):no(no),score(score){}
void Student::display()
{
    cout << no << ":" << score << endl;
}

int main()
{
    //定义对象数组

    Student stu[5] =
    {
        Student(100,100),
        Student(200,200),
        Student(300,300),
        Student(400,400),
        Student(500,500)
    };
    
    Student *p;//指定对象指针

    p = stu; //将对象数组的首地址赋值给指针对象

    for(int i = 0 ; i < 5; i++)
    {
        switch(i + 1)
        {
            case 1:
            case 3:
            case 5:
               (*p).display();
                break;
            default:
                break;
        }
        p++;
    }
    system("pause");
    return 0;
}


阅读(1277) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~