day13_对象型参数和返回值

对象类型作为函数的参数或者返回值,

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

class Car {
	int m_price;
public:
	Car(int price = 0) :m_price(price) { 
		cout << "Car(int) - " << this << " - " << this->m_price << endl;
	}

	Car(const Car &car) :m_price(car.m_price) {
		cout << "Car(const Car &) - " << this << " - " << this->m_price << endl;
	}
};
 
//void test1(Car &car) {
//
//}
void test1(Car car) {

}

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

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

	Car car2 = test2();

	// Car car3;
	// car3 = test2();


	getchar();
	return 0;
}

匿名对象(临时对象)

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


using namespace std;

class Person {
public:
	Person() {
		cout << "Person() - " << this << endl;
	}
	Person(const Person &person) {
		cout << "Person(const Person &person) - " << this << endl;
	}
	~Person() {
		cout << "~Person() - " << this << endl;
	}
	void display() {
		cout << "display()"  << endl;
	}
};

void test1(Person person) {

}

Person test2() {
	// Person person;
	return Person();
}

int main() {
	Person person1;
	person1 = test2();

	// Person person;

	// Person *p = new Person();

	// cout << 1 << endl;
	
	// Person().display();

	// cout << 2 << endl;

	// Person person;
	// test1(person);

	// test1(Person());

	// Person person = Person();

	getchar();
	return 0;
}

隐式构造

  • C++中存在隐式构造的现象:某些情况下,会隐式调用单参数的构造函数
  • 可以通过关键字explicit禁止掉隐式构造
using namespace std;

class Person {
	int m_age;
public:
	Person()  {
		cout << "Person() - " << this << endl;
	}
  //可以通过关键字explicit禁止掉隐式构造
	explicit Person(int age) :m_age(age) {
		cout << "Person(int) - " << this << endl;
	}
	Person(const Person &person) {
		cout << "Person(const Person &person) - " << this << endl;
	}
	~Person() {
		cout << "~Person() - " << this << endl;
	}
	void display() {
		cout << "display() - age is " << this->m_age << endl;
	}
};

void test1(Person person) {

}

Person test2() {
	return 30;
}

int main() {

	// test1(40);

	// Person person = test2();
	// Person person(10);
	// person = test2();

	Person person = 10;

	// Person person(10);
	person = 20;
	// person.display();
		
	getchar();
	return 0;
}

posted @ 2021-04-18 20:22  AAAAAAAAA123123  阅读(41)  评论(0编辑  收藏  举报