c++ 引用调用例子 形参指针 经典代码

#include<iostream>
#include<string>
using namespace std;
class Student
{
public:
string name;
int score;
Student(string name, int score)
{
this->name = name;
this->score=score;
cout << name << "的成绩是" << score << endl;
}
};
void show(Student &a, Student &b)
{

if (a.score < b.score)
{
cout << a.name << "比" << b.name << "的成绩低了" << -(a.score - b.score) << "分" << endl;
}
if (a.score > b.score)
{
cout << a.name << "比" << b.name << "的成绩高了" << a.score - b.score << "分" << endl;
}
if (a.score == b.score)
{
cout << "两者成绩一样" << endl;
}
}
int main()
{
Student s[] = { Student("Tom", 80),
Student("Jerry", 95),
Student("Garfield", 85) };
cout << endl;
show(s[0], s[1]);
show(s[1], s[2]);
return 0;

}


void show(Student &a, Student &b)其中引用调用是s[],用的是&符号


而另外一种


#include<iostream>
#include<string>
using namespace std;
class Goat
{
private:
string name;
int weight;


public:


Goat(string name, int weight)
{
this->name = name;
this->weight = weight;


}
void sleep()
{
int n = 2;
weight += n;
cout << name << "睡了一觉, 体重增长" << n << "斤" << endl;
}
string getName()
{
return name;
}
int getWeight()
{
return weight;


}
};
class Wolf
{


private:
string name;
int weight;
public:


Wolf(string name, int weight)
{
this->name = name;
this->weight = weight;
}


void eat(Goat *g)
{
int n = 95;
weight += n;
cout << name << "吃了" << (*g).getName() << ", 体重增长" << n << "斤" << endl;
}
string getName()
{
return name;
}
int getWeight()
{
return weight;


}
};
void print(Goat *g)
{
cout << (*g).getName() << "是一只" << (*g).getWeight() << "斤的羊" << endl;
}
void print(Wolf *w)
{
cout << (*w).getName() << "是一只" << (*w).getWeight() << "斤的狼" << endl;
}
int main()
{
Goat *g1 = new Goat("美羊羊", 95);
Goat *g2 = new Goat("暖羊羊", 120);
Wolf *w1 = new Wolf("小灰灰", 100);
print(g1);
print(g2);
print(w1);
g2->sleep();
w1->eat(g1);
print(g2);
print(w1);
return 0;
}

void print(Goat *g)中是将地址作为形参。


猜你喜欢

转载自blog.csdn.net/a66666_/article/details/79767406