我想在类似于原生类型的结构之间强制执行显式转换:
int i1;
i1 = some_float; // this generates a warning
i1 = int(some_float): // this is OK
int i3 = some_float; // this generates a warning
我想使用赋值运算符和复制构造函数来做同样的事情,但行为不同:
Struct s1;
s1 = other_struct; // this calls the assignment operator which generates my warning
s1 = Struct(other_struct) // this calls the copy constructor to generate a new Struct and then passes that new instance to s1's assignment operator
Struct s3 = other_struct; // this calls the COPY CONSTRUCTOR and succeeds with no warning
是否有任何技巧可以使用默认构造函数获取第三种情况Struct s3 = other_struct;
构造 s3 然后调用赋值运算符?
这一切都按应有的方式编译和运行。C++ 的默认行为是在创建新实例并立即调用复制构造函数时调用复制构造函数而不是赋值运算符,(即MyStruct s = other_struct;
变为MyStruct s(other_struct)
; 不是MyStruct s; s = other_struct;
。我只是想知道是否有任何技巧可以解决这个问题.
编辑:“显式”关键字正是我所需要的!
class foo {
foo(const foo& f) { ... }
explicit foo(const bar& b) { ... }
foo& operator =(const foo& f) { ... }
};
foo f;
bar b;
foo f2 = f; // this works
foo f3 = b; // this doesn't, thanks to the explicit keyword!
foo f4 = foo(b); // this works - you're forced to do an "explicit conversion"