简体   繁体   English

使用类的编译器的行为

[英]behavior of the compiler using classes

#include <list>
using std::list;
class foo { ...
class bar : public foo { ...
static void print_all(list<foo*> &L) { ...
list<foo*> LF;
list<bar*> LB;
...
print_all(LF); // works fine
print_all(LB); // static semantic error

I think i know why the compiler will not allow the second call. 我想我知道为什么编译器将不允许第二个调用。 Can anyone give an example of bad things that could happen if the compiler accepts this kind of call? 任何人都可以举一个如果编译器接受这种调用可能发生的坏事的例子吗?

Sure! 当然! What if print_all does this: 如果print_all这样做怎么办:

L.push_back(new Foo);

Now your list of Bar pointers has a pointer to a Foo object that is not a Bar. 现在,您的Bar指针列表具有一个指向不是Bar的Foo对象的指针。 If you then try to call a method in Bar not present in the Foo class, you'll get some sort of serious runtime problem since the method doesnt exist in the Foo object. 如果然后尝试在Foo类中不存在的Bar中调用方法,则会遇到某种严重的运行时问题,因为该方法在Foo对象中不存在。

Hope this helps! 希望这可以帮助!

There are two different things going on in the code, with different explanations. 代码中有两种不同的情况,有不同的解释。 The first problem is that different instantiations of a template are unrelated, even if the instantiating types are related. 第一个问题是,即使实例化类型相关,模板的不同实例化也不相关。 In this particular case std::list<foo*> has no relationship with std::list<bar*> , even if foo is a base of bar . 在这种特殊情况下,即使foobar的基础, std::list<foo*>std::list<bar*>也没有关系。 This is part of the design of the language and nothing can be done. 这是语言设计的一部分,什么也做不了。

The second problem, which is not what the compiler is complaining about is that in general a container of derived cannot be used by reference as a container of base . 第二个问题(不是编译器在抱怨的问题)是,通常,不能将derived的容器作为引用用作base的容器。 That is the issue that @templatetypedef brought up --but again, this is not the issue in the code, it would be in a different example: 这就是@templatetypedef带来的问题-但是,这又不是代码中的问题,而是另一个示例:

void f( base** p );
int main() {
   derived *d;
   f( &d );          // error
}

In this case, the issue is that, as @templatetypedef points out that using a pointer/container of derived in place of a pointer/container to base in a non-const manner is prone to errors, as you could store non- derived types on the pointer/container. 在这种情况下,这个问题是,随着@templatetypedef指出使用的指针/容器derived代替指针/容器的base 在一个非const方式是容易出错,因为你可以存储非derived类型在指针/容器上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM