#include
#include
using namespace std;
class phone
{
public:
phone()
{}
phone(string name)
{
p_name = name;
cout << "phone有参构造" << endl;
}
~phone()
{
cout << "phone的析构函数" << endl;
}
string p_name;
};
class student
{
public:
student(string m_name, int m_score, int m_high, string p_name):name(m_name),score(m_score),high(new int(m_high)),pname(m_name){}
~student()
{
cout << "student的析构函数" << endl;
}
void pnames()
{
cout << name << "拿着" << pname.p_name << "手机" << endl;
}
public:
string name;
int score;
int* high;
phone pname;
};
int main()
{
student s;
}
默认构造函数即为无参构造函数,当你为自定义的类添加了其他带参数的构造函数时,编译器不再自动的为你添加默认构造函数,再这种情况下,如果你需要使用默认构造函数来构造对象,就必须手动填上无参的构造函数。
你的student类只有带参数的构造函数,而main函数中student s;调用的是无参构造函数,所以编译器会报错提示没有相应的默认构造函数。
相反地,如果你没有给编译器提供任何构造函数,编译器会默认提供简单的无参的默认构造函数(编译器自动提供的默认构造函数的函数体是空的,不做任何事情)
类如果没有声明构造函数就使用的是无参构造。如果声明了带参构造。这个隐式的无参构造就不存在了。如果想要使用就需要自行的添加。
你这里使用了带参但是没有声明无参,想要通过无参构造进行创建实例肯定会报错。
student s("xiaoming",1,1,"iphone");这样构造