那为什么 p = new student;显示student没有构造函数呢
时间: 2023-09-10 19:09:17 浏览: 46
在 `teacher` 类的构造函数中,执行了 `p = new student;` 语句,其中 `new` 运算符会调用 `student` 类的默认构造函数来创建一个新的 `student` 类对象,并返回指向该对象的指针。但是在 `student` 类中定义了一个带参的构造函数,而没有定义默认构造函数,因此编译器无法自动为其生成默认构造函数。因此,在 `teacher` 类中使用 `new` 运算符来创建 `student` 类对象时,会出现 "没有匹配的函数" 的编译错误。
为了解决这个问题,可以在 `student` 类中定义一个默认构造函数,或者在 `teacher` 类的构造函数中调用 `student` 类的带参构造函数来创建对象。例如,可以将 `teacher` 类的构造函数修改为:
```c++
teacher::teacher(int a) {
cout << "teacher构造函数调用" << endl;
this->a = a;
p = new student(0); // 调用 student 类的带参构造函数,初始化 a 的值为 0
}
```
这样就可以在 `teacher` 类中成功创建 `student` 类对象了。
相关问题
Student student = new Student()和Student student = new Stident(1)区别
`Student student = new Student()`和`Student student = new Student(1)`是两个不同的语句,有以下区别:
1. `Student student = new Student()`创建了一个新的`Student`对象,并将其赋值给名为`student`的变量。这是一个无参数的构造函数调用,不传递任何参数给构造函数。这意味着创建的`Student`对象的属性会使用默认值进行初始化。
2. `Student student = new Student(1)`创建了一个新的`Student`对象,并将其赋值给名为`student`的变量。这是一个带有参数的构造函数调用,将整数值1作为参数传递给构造函数。这意味着创建的`Student`对象在初始化时会接收到参数值,并使用该值对属性进行初始化。
总结来说,`Student student = new Student()`创建一个使用默认构造函数初始化的`Student`对象,而`Student student = new Student(1)`创建一个使用带参数构造函数初始化,并传递整数值1的`Student`对象。因此,在使用这两个语句时需要注意它们之间的区别和可能导致的属性初始化差异。
1创建一个student类 要求有nameagesex三个属性、私有属性,要求做封装。 . 2.建立一个无参的构造函数, 输出“无参构造函数。 3.建立一个含name的构造函数,输出“ 含name构造函数, 4.建立一个含name、age、 sex 的构造函数,输出“含name +age+ sex的构造函数。.5.在有一个参数的构造函数中调用一个无参的构造 函数。。 创建对像 student a=new student(): Student b=new student["张三) Studentc-newstudent("张三18r男D)→
非常抱歉,我可以回答这个问题。以下是一个示例的student类的代码:
```java
public class Student {
private String name;
private int age;
private String sex;
public Student() {
System.out.println("无参构造函数。");
}
public Student(String name) {
this.name = name;
System.out.println("含name构造函数。");
}
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
System.out.println("含name age sex的构造函数。");
}
public Student(String name) {
this();
this.name = name;
System.out.println("含一个参数的构造函数,调用了无参构造函数。");
}
public static void main(String[] args) {
Student a = new Student();
Student b = new Student("张三");
Student c = new Student("张三", 18, "男");
}
}
```
注意,这里的构造函数都是公有的,因为私有的构造函数无法在外部调用。如果需要封装,可以将构造函数设为私有,然后提供公有的静态方法来创建对象。