N***m 发帖数: 4460 | 1 c++ forbids implicit conversion of user-defined type more than once.
所以试验了一下。
首先是不是只能这样写?能不能用member function之类的?
假定ABC没有继承关系。
这样写起来很麻烦,如果有好多层转换A->B->C...的话。
有没有简化的写法?
======================================================================
#include
using namespace std;
class C {
int i;
public:
C(int j):i(j){}
void Print(){cout<<"C::i="<
};
class B {
int i;
public:
B(int j):i(j){}
operator C()
{
return C(3*i);
}
void Print(){cout<<"B::i="<
};
cla |
z****e 发帖数: 2024 | 2 你可以不必
operator C()
{
return C(operator B());
}
直接
operator C()
{
return C(6*i);
} |
z****e 发帖数: 2024 | 3 或者给C加几个constructor,takeA,B。 |
N***m 发帖数: 4460 | 4 right, in this particular example,
you can always do this straightforwardly.
But I "feel" this is not a somewhat good design, since you need to
know the very details of every conversion. Suppose you change the
implementation of B, then you need to worry about C.
It is easy to make some mistakes here and there.
So are there any smart or simple patterns to follow?
【在 z****e 的大作中提到】 : 你可以不必 : operator C() : { : return C(operator B()); : } : 直接 : operator C() : { : return C(6*i); : }
|
N***m 发帖数: 4460 | 5 这个本质上和C(A()),C(B())是差不多的吧?
要是有很多转换,写起来还是麻烦的。
不过,我自己也没想清楚我究竟想说什么:)
【在 z****e 的大作中提到】 : 或者给C加几个constructor,takeA,B。
|
t****t 发帖数: 6806 | 6 this is part of class interface design. it's not something with a generic
rule or what you can know in a snap. usually it depends on how your client (
probably yourself) want to use the class.
but most conversion function should be in contructor form, instead of
operator T() form. see EC++.
【在 N***m 的大作中提到】 : 这个本质上和C(A()),C(B())是差不多的吧? : 要是有很多转换,写起来还是麻烦的。 : 不过,我自己也没想清楚我究竟想说什么:)
|
N***m 发帖数: 4460 | 7 I see.thanks for your reply.
(
【在 t****t 的大作中提到】 : this is part of class interface design. it's not something with a generic : rule or what you can know in a snap. usually it depends on how your client ( : probably yourself) want to use the class. : but most conversion function should be in contructor form, instead of : operator T() form. see EC++.
|
k*******d 发帖数: 1340 | 8 You mean non-explicit constructor?
generic
client (
【在 t****t 的大作中提到】 : this is part of class interface design. it's not something with a generic : rule or what you can know in a snap. usually it depends on how your client ( : probably yourself) want to use the class. : but most conversion function should be in contructor form, instead of : operator T() form. see EC++.
|
t****t 发帖数: 6806 | 9 yes, obviously non-explicit. otherwise you can't do implicit conversion.
【在 k*******d 的大作中提到】 : You mean non-explicit constructor? : : generic : client (
|