我创建了一个名为Rectangle的类并实现了一个参数化构造函数并创建了 Rectangle 类的三个实例
#include<iostream>
using namespace std;
class Rectangle {
private:
int length;
int bredth;
public:
Rectangle(int l=0, int b=0) {
length=l;
bredth=b;
}
};
int main() {
system("clear");
Rectangle r1;
Rectangle r2(10, 5);
Rectangle r3=Rectangle(10, 5);
return 0;
}
编译此源代码文件时没有问题。
但是在实现复制构造函数之后,我得到了一个错误。
#include<iostream>
using namespace std;
class Rectangle {
private:
int length;
int bredth;
public:
Rectangle(int l=0, int b=0) {
length=l;
bredth=b;
}
Rectangle(Rectangle &r) {
length=r.length;
bredth=r.bredth;
}
};
int main() {
system("clear");
Rectangle r1;
Rectangle r2(10, 5);
Rectangle r3=Rectangle(10, 5);
Rectangle r4=r3;
return 0;
}
错误信息
3.cpp:24:14: error: no matching constructor for initialization of 'Rectangle'
Rectangle r3=Rectangle(10, 5);
^ ~~~~~~~~~~~~~~~~
3.cpp:10:7: note: candidate constructor not viable: no known conversion from 'Rectangle' to 'int' for 1st argument Rectangle(int l=0, int b=0) { ^
3.cpp:14:7: note: candidate constructor not viable: expects an lvalue for 1st argument
Rectangle(Rectangle &r) {
^
1 error generated.
为什么在实现复制构造函数之后会发生这种情况,并且只针对显式构造函数调用?