[C++ Study Notes 6] Experiment 6 - Basic knowledge of classes and objects (3)

Case:
object array and traversal
Create an array of car objects, instantiate the object elements with anonymous objects , then traverse the object array and access the display method of each element.
Input:
None
Output:
Audi 230,000
BMW 350,000
Mercedes Benz 400,000

#include <iostream>
#include<string>
using namespace std;
class Car{
    
    
private:
	string brand;
	double price;
public:
	Car(){
    
    
	}
	Car(string brand,double price){
    
    
		this->brand = brand;
		this->price = price;
	}	
	void display(){
    
    
		cout<<this->brand<<" "<<this->price<<endl;
	}
};

int main(){
    
     


//cout<<"奥迪 230000\n宝马 350000\n奔驰 400000"<<endl;
Car("奥迪",230000).display();//匿名对象实例化
Car("宝马",350000).display();
Car("奔驰",400000).display();


	return 0;
}

Case:
function parameter type, ordinary object, object reference, object pointer

Create a method according to the requirements:
showStudent1 method, the parameter type is an ordinary object , output the prompt "object is used as a function parameter", and call the object display method
showStudent2 method, the parameter type is an object pointer , output the prompt "object pointer is used as a function parameter", and point to the display Method
showStudent3 method, parameter type is object reference , output "object reference as function parameter" prompt, and call object display method.

input:
none

Output:
object as function parameter
Zhang Bao22
object pointer as function parameter
Jin Tian25
object reference as function parameter
Wang Yong25

#include <iostream>
#include<string>
using namespace std;
class Student
{
    
    
	string name;
	int age;                           
public:
	//构造函数
	Student(){
    
    
	}
	Student( string name , int age){
    
    
		this->name = name;
		this->age = age;
	}
	void display(){
    
    
		cout<<this->name<<" "<<this->age<<endl;
	}
};



//对象作为函数参数
void showStudent1(Student std){
    
    
//实参的值std传给形参std,方法内改变形参,对实参无影响
    cout<<"对象作为函数参数"<<endl;
    std.display();
}
//对象指针作为函数参数
void showStudent2(Student* std){
    
    
//形参std是对象的指针,实参&std2是对象的地址值,方法内改变std相当于改变std2
    cout<<"对象指针作为函数参数"<<endl;
    std->display();
}
//对象引用作为函数参数
void showStudent3(Student& std){
    
    
//等于给std3起了一个“std”的小名,方法内改变std相当于改变std3
    cout<<"对象引用作为函数参数"<<endl;
    std.display();
}

//引用与指针的区别是:引用相当于起别名,指针相当于通过指针这个媒介访问地址

int main(){
    
     
	Student std("张宝",22);
	showStudent1(std);

	Student std2("金天",25);
	showStudent2(&std2);

	Student std3("王勇",25);
	showStudent3(std3);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_49868778/article/details/115560523