对象类型的参数和返回值、匿名对象

对象类型的参数和返回值

使用对象类型作为函数的参数或者返回值,可能会产生一些不必要的中间对象。

例题1

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

void test1(Car car) {

}

int main() {
	
	Car car1;
	test1(car1);

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第1张图片

例题2

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

Car test2() {
	Car car;
	return car;
}

int main() {

	Car car2;
	car2 = test2();

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第2张图片

例题3

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

//void test1(Car car) {
//
//}

//Car test2() {
//	return Car();
//}

Car test2() {
	Car car;
	return car;
}

int main() {

	Car car3 = test2();

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第3张图片

匿名对象(临时对象)

匿名对象:没有变量名、没有被指针指向的对象,用完后马上调用析构。

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

int main() {
	
	cout << 1 << endl;
	Car().run();
	cout << 2 << endl;

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第4张图片

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

void test1(Car car) {

}

//Car test2() {
//	return Car();
//}

//Car test2() {
//	Car car;
//	return car;
//}

int main() {

	test1(Car());

	//
	//cout << 1 << endl;
	//Car().run();
	//cout << 2 << endl;
	
	//Car car1;
	//test1(car1);

	// Car car2; // Car()
	// car2 = test2();

	//Car car3 = test2();

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第5张图片

#include 
using namespace std;

class Car {
public:
	Car() {
		cout << "Car() - " << this << endl;
	}

	Car(const Car &car) {
		cout << "Car(const Car &) - " << this << endl;
	}

	~Car() {
		cout << "~Car() - " << this << endl;
	}

	void run() {
		cout << "run()" << endl;
	}
};

Car test2() {
	return Car();
}

int main() {

	Car car2;
	car2 = test2();

	getchar();
	return 0;
}

对象类型的参数和返回值、匿名对象_第6张图片

你可能感兴趣的:(重学C++,c++)