简体   繁体   English

在C ++中,是否允许将其强制转换为仅添加非虚拟方法的派生类?

[英]In C++, is it allowed to cast to a derived class that only adds non-virtual methods?

I'd like to add non-virtual methods to an existing class A that I can't change. 我想将非虚拟方法添加到我无法更改的现有类A中。 Therefore I create a class B inherited from A and add the methods I want. 因此,我创建了一个从A继承的类B ,并添加了我想要的方法。 Now, if I have an object of type A , can I just regard it as an object of type B ? 现在,如果我有一个类型为A的对象,是否可以将其视为类型为B的对象? Say, is the following code legal?: 说,以下代码合法吗?

class A { <...> };

class B: public A {
    void f();
  };

A a();
void g( const B& );
void h() { g( static_cast<B&&>(a()) ); }

It does compile and work, however I was wondering if it's guaranteed by the standard to work as expected. 它确实可以编译和工作,但是我想知道标准是否保证它可以按预期工作。 I don't see why not, yet it doesn't feel very clean.. 我不明白为什么不这样做,但是感觉不太干净。

That is undefined behavior. 那是未定义的行为。 From [expr.static.cast] : 来自[expr.static.cast]

An lvalue of type “cv1 B”, where B is a class type, can be cast to type “reference to cv2 D”, where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The result has type “cv2 D”. 如果从“指针到”的有效标准转换,则类型为“ cv1 B”的左值(其中B是类类型)可以转换为“对cv2 D的引用”,其中D是从B派生的类(第10条)。存在“ D”到“指向B的指针”(4.10),cv2与cv1具有相同的cv限定,或者具有比cv1更大的cv限定,并且B既不是D的虚拟基类也不是虚拟基类的基类D的结果。类型为“ cv2 D”。 An xvalue of type “cv1 B” may be cast to type “rvalue reference to cv2 D” with the same constraints as for an lvalue of type “cv1 B”. 可以将类型“ cv1 B”的xvalue强制转换为类型“对cv2 D的rvalue引用”,其约束与对类型“ cv1 B”的lvalue的约束相同。 If the object of type “cv1 B” is actually a subobject of an object of type D, the result refers to the enclosing object of type D. Otherwise, the behavior is undefined. 如果类型“ cv1 B”的对象实际上是类型D的对象的子对象,则结果将引用类型D的封闭对象。否则,行为是不确定的。

a isn't actually a suboject of an object of type B - it's really just of type A , so the behavior is undefined. a实际上不是类型B的对象的主体-实际上只是类型A ,因此行为是不确定的。

What's to stop you from simply adding a non-member function: 是什么使您无法简单地添加非成员函数:

void f(A& ); 

If the answer is that you need to access private or protected members of A , then there was intent to make those members unaccessible to you! 如果答案是您需要访问A privateprotected成员,则有意使您无法访问这些成员!

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

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