问题描述
我想知道是否可能让编译器针对代码发出警告/错误,如下所示:
注意: p>
1。是的,它是坏的编程风格,我们应该避免这种情况 - 但我们在处理遗留代码,希望编译器可以帮助我们识别这种情况。)
2。我喜欢使用编译器选项(VC ++)禁用或启用对象切片(如果有)。
{};
class Derived:public Base {};
void Func(Base)
{
}
// void Func(Derived)
// {
//
//}
// main
Func(Derived());
在这里,如果我注释掉第二个函数,第一个函数将被调用 - 编译器VC ++和Gcc)感觉很舒服。
是C ++标准吗?并且我可以请求编译器(VC ++)在遇到这样的代码时给我一个警告。
感谢这么多!!!
编辑:
非常感谢您的帮助!
我找不到编译器选项给出错误/警告 - 我甚至发布在MSDN论坛为VC ++编译器顾问没有答案。所以我恐怕gcc和vc ++都没有实现这个特性。
所以添加构造函数,派生类作为参数是最好的解决方案。
编辑
我已经向MS提交了一个feedbak,希望他们尽快解决:
-Baiyan
如果你可以修改基类,你可以这样做:
class Base
{
public:
//未实现将导致链接错误
Base(const Derived& d);
const Base& operator =(const Derived& rhs);
};
根据你的编译器,你应该得到翻译单元,也许切片发生的功能。
I want to know if it is possible to let compiler issue a warning/error for code as following:
Note:
1. Yea, it is bad programming style and we should avoid such cases - but we are dealing with legacy code and hope compiler can help identify such cases for us.)
2. I prefer a compiler option (VC++) to disable or enable object slicing, if there is any.
class Base{};
class Derived: public Base{};
void Func(Base)
{
}
//void Func(Derived)
//{
//
//}
//main
Func(Derived());
Here if I comment out the second function, the first function would be called - and the compiler (both VC++ and Gcc) feels comfortable with that.
Is it C++ standard? and can I ask compiler (VC++) to give me a warning when met such code?
Thanks so much!!!
Edit:
Thanks all so much for your help!
I can't find a compiler option to give a error/warning - I even posted this in MSDN forum for VC++ compiler consultant with no answer. So I am afraid neither gcc nor vc++ implemented this feature.
So add constructor which take derived classes as paramter would be the best solution for now.
Edit
I have submit a feedbak to MS and hope they will fix it soon:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=421579
-Baiyan
If you can modify the base class you could do something like:
class Base
{
public:
// not implemented will cause a link error
Base(const Derived &d);
const Base &operator=(const Derived &rhs);
};
Depending on your compiler that should get you the translation unit, and maybe the function where the slicing is happening.
这篇关于如何在对象切片时生成编译器警告/错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!