//建立一个对象数组,内放5个学生的数据,用指针指向数组首元素,输出第1,3,5个学生的数据
#include<iostream>
#include <string>
using namespace std;
class Student
{
public:
int number;
string name;
};
int main()
{
Student student[5];//定义对象数组
Student *p=student;//初始化指针p指向对象数组student的首地址
int num=1001;//为了初始化数组对象中的number
string nam[5]={"张三","李四","王五","丽丽","小强"};//初始化数组对象中的name
int i=0,k=0;
for(i=0;i<5;i++)
{
k=i+1;
student[i].number=num;
num++;
student[i].name=nam[i];
if (k==1||k==3||k==5)
{
cout<<"第"<<i+1<<"个学生的学号为:";
cout<<p[i].number<<" ";
cout<<"名字为:";
cout<<p[i].name<<endl;
cout<<endl;
}
}
cout<<endl;
return 0;
}
运行结果为:
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n=0, float s=0): num(n), score(s){}
void input();
void display();
private:
int num;
float score;
};
void Student::input()
{
cin>>num>>score;
}
void Student::display()
{
cout<<num<<' '<<score<<endl;
}
int main()
{
Student stu[5], *p;
int i;
for (i=0; i<5; i++){
cout<<"Pleas enter No."<<i+1<<" student info: ";
stu[i].input();
}
for (p=stu; p<stu+5; p+=2){
p->display();
cout<<endl;
}
system("pause");
return 0;
}
cout语句的一般格式为:
cout<<表达式1<<表达式2<<……<<表达式n;
在定义流对象时,系统会在内存中开辟一段缓冲区,用来暂存输入输出流的数据。在执行cout语句时,先把插入的数据顺序存放在输出缓冲区中,
直到输出缓冲区满或遇到cout语句中的endl(或'\n',ends,flush)为止,此时将缓冲区中已有的数据一起输出,并清空缓冲区。输出流中的数据在系统默认的设备(一般为显示器)输出。
一个cout语句可以分写成若干行。如:
cout<<"This is a simple C++ program."<<endl;
可以写成
cout<<"This is " //注意行末尾无分号
<<"a C++ "
<<"program."
<<endl; //语句最后有分号
也可写成多个cout语句,即
cout<<"This is "; //语句末尾有分号
cout <<"a C++ ";
cout <<"program.";
cout<<endl;
以上3种情况的输出均为:
This is a simple C++ program.