我正在尝试复制字符串类函数,我们可以在同一行中声明和分配字符串类对象值某个右值。
例如字符串 s1 = "你好"
但我试图用整数来做。我的代码是这样的。
#include <iostream>
using namespace std;
class Foo {
private:
int a;
public:
Foo () {
}
explicit Foo(int a) {
this->a = a;
}
Foo(Foo &obj) {
this->a = obj.a;
}
void operator= (int a) {
cout<<"operator called "<<endl;
this->a=a;
}
void print() {
cout<<"a is "<<this->a<<endl;
}
};
int main () {
Foo obj2 = 10; // Getting error here (no int to Foo conversion found)
obj2.print();
return 0;
}
我知道从我的单参数构造函数中删除显式(即使其成为转换构造函数)可以解决问题,但我想保持 ctor 为显式。有什么办法可以做到这一点?我也尝试重载“=”赋值运算符,但没有运气。请帮忙。