c++构造函数不能使用本class对象作为参数

 

root@romulus-laptop:/work/test/operator_1# cat main.c student.h student.cpp #include #include"student.h" int main(void) { student stu1; } class student { public: student(const student s); }; #include"student.h" student::student(const student s) { } root@romulus-laptop:/work/test/operator_1# g++ -o main *.c *.cpp In file included from main.c:2: student.h:4: error: invalid constructor; you probably meant ‘student (const student&)’ In file included from student.cpp:1: student.h:4: error: invalid constructor; you probably meant ‘student (const student&)’ student.cpp:2: error: prototype for ‘student::student(student)’ does not match any in class ‘student’ student.h:2: error: candidates are: student::student(const student&) student.h:2: error: student::student()

1. 原因在于:即使编译通过,那么对象拷贝是调用了拷贝构造函数,这是拷贝构造函数的参数传递也需要调用拷贝构造函数来完成对象参数拷贝,造成死循环,因此编译器不允许这样的构造函数出现

 

2. 分析:

root@romulus-laptop:/work/test/operator_1# g++ -o main *.c *.cpp
In file included from main.c:2: // 包含头文件发现构造函数原型错误
student.h:4: error: invalid constructor; you probably meant ‘student (const student&)’ // 提示student (const student s)应该写成student (const student&)


In file included from student.cpp:1: // 包含头文件发现构造函数原型错误
student.h:4: error: invalid constructor; you probably meant ‘student (const student&)’ // 提示student (const student s)应该写成student (const student&)


student.cpp:2: error: prototype for ‘student::student(student)’ does not match any in class ‘student’ // 函数定义student::student(student)’在下面两个候选声明中找不到对应的函数声明
student.h:2: error: candidates are: student::student(const student&)
student.h:2: error:                 student::student()

你可能感兴趣的:(C/C++基础)