y*h 发帖数: 107 | 1 我写了个class, 并只给了它一个constructor(int)
class A
{
A(int a){}
};
可现在在main function里面A(double) 照运行无误, 一点也不报错.
如何改程序, 让其robust, 见A(double)报错. |
q*****g 发帖数: 72 | 2 implicit conversion from double to int.
try writing a private A(double)
【在 y*h 的大作中提到】 : 我写了个class, 并只给了它一个constructor(int) : class A : { : A(int a){} : }; : 可现在在main function里面A(double) 照运行无误, 一点也不报错. : 如何改程序, 让其robust, 见A(double)报错.
|
y*h 发帖数: 107 | 3 这样行不行? 试了一下能运行, 大家说说有无memory leak?
class A
{
public:
A(int){}
A(double){exit(-1);}
}
【在 q*****g 的大作中提到】 : implicit conversion from double to int. : try writing a private A(double)
|
q*****g 发帖数: 72 | 4 no memory leak, but not a good design.
the program will terminate suddenly if someone use A(double)
【在 y*h 的大作中提到】 : 这样行不行? 试了一下能运行, 大家说说有无memory leak? : class A : { : public: : A(int){} : A(double){exit(-1);} : } :
|
c*r 发帖数: 278 | 5 explicit A(int a) {}
【在 y*h 的大作中提到】 : 这样行不行? 试了一下能运行, 大家说说有无memory leak? : class A : { : public: : A(int){} : A(double){exit(-1);} : } :
|
X****r 发帖数: 3557 | 6 No, "explicit" keyword only prevents implicit conversion from int to A. It
won't prevent the floating-integral conversion from double to int. The right
way is defining a private A(double) as mentioned above.
【在 c*r 的大作中提到】 : explicit A(int a) {}
|
b*****n 发帖数: 2324 | 7 服了,够彻底,你的exit了还能有啥leak。
【在 y*h 的大作中提到】 : 这样行不行? 试了一下能运行, 大家说说有无memory leak? : class A : { : public: : A(int){} : A(double){exit(-1);} : } :
|
l***t 发帖数: 81 | |