#include <iostream>
using namespace std;
class Student {
public:
Student(int n = 0, int s = 0) {
num = n;score = s;
}
void display()
{
cout << num << " " << score << endl;
}
private:
int num;
int score;
};
int main()
{
Student stu[5]={ Student(101,98),Student(102,99),Student(103,88),Student(104,87),Student(105,99)};
Student* p = stu;
p->display();
(p + 2)->display();
(p + 4)->display();
return 0;
}
#include <iostream>
using namespace std;
class Student {
public:
Student(int n = 0, int s = 0) {
num = n;score = s;
}
void display()
{
cout << num << " " << score << endl;
}
int num;
int score;
};
void max(Student* p) {
int maxs=p->score, maxn=p->num, i;
for (i = 0;i < 5;i++) {
if (((p + i)->score) > maxs)
{
maxs = (p + i)->score; maxn = (p + i)->num;
}
}
cout << maxn << " " << maxs;
}
int main()
{
void max(Student * p);
Student stu[5]={ Student(101,98),Student(102,95),Student(103,88),Student(104,87),Student(105,99)};
Student* p = stu;
max(p);
return 0;
}
8.对象的引用
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,float s):num(n),score(s){}
void change(int n, float s) {
num = n;
score = s;
}
void display() {
cout << num << " " << score << endl;
}
private:
int num;
float score;
};
void fun(Student& stu) {
stu.display();
stu.change(103, 99);
stu.display();
}
int main()
{
void fun(Student & stu);
Student stu(101,97);
fun(stu);
return 0;
}
9.利用静态数据和静态成员函数,计算商品的平均价格和总收入
#include <iostream>
using namespace std;
class Product {
public:
Product(int m, int n, float p) :num(m), quantity(n), price(p) {};
void total();
static float average();
static void display();
private :
int num; //销货员号
int quantity;//件数
float price;//单价
static float discount;//统一折扣
static float sum;//总销售款
static int n;//总件数
};
void Product::total() {
float rate = 1.0;
if (quantity > 10) rate = 0.98 * rate;
sum = sum + quantity * rate * price * (1 - discount);
n = n + quantity;
}
float Product::average() {
return sum / n;
}
void Product::display() {
cout << sum << endl;
cout << average() << endl;
}
//对静态成员初始化
float Product::discount = 0.05;
float Product::sum = 0;
int Product::n = 0;
int main() {
Product pro[3] = {
Product(101,5,23.5),
Product(102,12,24.56),
Product(103,100,21.5)
};
for (int i = 0;i < 3;i++) {
pro[i].total();
}
Product::display();//调用静态成员函数
return 0;
}
12.在类模板外定义成员函数
template <class numtype>
class Compare {
public:
Compare(numtype a, numtype b);
numtype max();
numtype min();
private:
numtype x, y;
};
template <class numtype>
Compare<numtype>::Compare(numtype a, numtype b) {
x = a;y = b;
}
template <class numtype>
numtype Compare<numtype>::max() {
if (x > y) return x;
return y;
}
template <class numtype>
numtype Compare<numtype>::min() {
if (x < y) return x;
return y;
}