假设我们现在存在一个Student类,类里我们声明的三个构造函数:默认构造函数,有参(参数列表是 int a)构造函数,拷贝构造函数。
那么,在我们声明一个变量时有三种方法,一种是括号法,显示法,隐式转化法。
括号法:
Student st1; //默认构造函数
Student st2(5); //有参构造函数
Student st3(st2); //拷贝构造函数
显示法:
Student st1=Student(5); //有参构造函数
Student st2=Student(st1); //拷贝构造函数
//这里值得注意的Student(5)是匿名对象 如果不让他赋值给别人的话 过完那一行就会被析构
//但是这里我们相当于给他起了一个别名,所以并不会析构
//还有,cpp不允许对象的指针或引用指向匿名对象,因为匿名对象是常量。
//如果我们在函数传值的时候想要让一个变量接受匿名对象 :1.用普通变量接 2.用引用的方式接收时要加const
//当匿名对象被一个普通对象接受后 是可以更改的 这个时候就是那个普通对象了
#include<iostream>
using namespace std;
class Student
{
public:
Student()
{
m_a = 10;
}
Student(int a)
{
m_a = a;
}
void show_answer()
{
cout << m_a;
}
private:
int m_a;
};
void receive(const Student&s)
{
}
void receive2(Student s)
{
s.show_answer();
}
void test01()
{
receive(Student(10));
}
void test02()
{
receive2(Student(50));
}
int main()
{
test01();
test02();
return 0;
}
隐式转化法:
Student st1=4; //这里会将隐式转化为显示 Student st1=Student(4) 调用了有参构造函数
Student st2=st1; //这里会将隐式转化为显示 Studnet st2=Student (st1) 调用了拷贝构造函数
//注意 我们不能利用拷贝构造函数初始化匿名对象
Student (st2);
//这个时候编译器会认为你是对 st2的重新定义