【发布时间】:2011-04-13 19:56:06
【问题描述】:
我想强制在类似于原生类型的结构之间进行显式转换:
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);而不是@987654326 @. 我只是想知道是否有任何技巧可以解决这个问题。
编辑:“显式”关键字正是我所需要的!
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"
【问题讨论】:
-
请发布一些精简版的真实代码。同时发布警告和错误。在我看来,您想做一些非常愚蠢的事情,而编译器正在告诉您。
-
@San Jacinto:我认为 Chris 想要以这样的方式编写类.
-
等等,这个问题有没有根本性的改变?
-
@John:不,它没有。我只是措辞更好。
标签: c++ copy-constructor assignment-operator