我从这个条目中看到虚拟继承将sizeof(指针)添加到对象的内存占用.除此之外,默认情况下使用虚拟继承是否有任何缺点,只有在需要时才使用常规继承?这似乎会带来更具前瞻性的课堂设计,但也许我错过了一些陷阱.
当前,我处于一些基类和许多子类的情况。子类必须重写多个虚拟方法,但是,有时一个子类中虚拟方法的实现与另一子类完全相同。我应该只复制实现代码并将其粘贴到另一个子类中,还是可以同时表达两个子类的实现?
下面的代码演示了我的问题。
class A
{
virtual void foo1() = 0;
virtual void foo2() = 0;
};
class B : public A
{
void foo1();
void foo2();
};
class C : public A
{
void foo1();
void foo2();
};
class D : public A
{
void foo1();
void foo2();
};
void B::foo1()
{
// Same implementation of foo1 as C
}
void C::foo1()
{
// Same implementation of foo1 as B
}
void D::foo1()
{
// Different implementation of foo1
} …Run Code Online (Sandbox Code Playgroud) 为什么结果是“B”,我认为它应该命中第一个继承类(“A”)?当我使用不从 A 类继承任何内容的 B 类运行它时,它会遇到第一个 catch 块,但我不知道下面的代码中出现这样的行为的原因:
#include <iostream>
#include <exception>
using namespace std;
class A {};
class B : public A{};
class C : public A, public B {};
int main() {
try {
throw C();
}
catch (A a) {
cout << "A" << endl;
}
catch (B b) {
cout << "B" << endl;
}
catch (C c) {
cout << "C" << endl;
}
}
Run Code Online (Sandbox Code Playgroud) 我想了解为什么 C++ 标准要求虚拟基非默认构造函数不能由中间非最派生类调用,如这段代码中所示,当使用 '-D_WITH_BUG_' 编译时:
/* A virtual base's non-default constructor is NOT called UNLESS
* the MOST DERIVED class explicitly invokes it
*/
#include <type_traits>
#include <string>
#include <iostream>
class A
{
public:
int _a;
A(): _a(1)
{
std::cerr << "A() - me: " << ((void*)this) << std::endl;
}
A(int a): _a(a)
{
std::cerr << "A(a) - me:" << ((void*)this) << std::endl;
}
virtual ~A()
{
std::cerr << "~A" << ((void*)this) << std::endl;
}
};
class B: public virtual …Run Code Online (Sandbox Code Playgroud) 有什么区别
Class A {};
Class Z: public A {};
Run Code Online (Sandbox Code Playgroud)
和
Class A {};
Class Z: virtual public A{};
Run Code Online (Sandbox Code Playgroud) 我有一个派生自两个相同基础的类:
class Vector3d {...};
class Position:public Vector3d {...};
class Velocity:public Vector3d {...};
class Trajectory:public Position, public Velocity
{
Vector3d &GetPosition(void);
Vector3d &GetVelocity(void);
};
Run Code Online (Sandbox Code Playgroud)
我想在派生类中有一个成员函数来快速转换为一个或另一个基类.我在想的是:
Vector3d &GetPosition(void) const
{
return static_cast<const Vector3d &>(*this);
}
Run Code Online (Sandbox Code Playgroud)
但我从编译器收到一条消息:"用'const Position'初始化的引用,需要'Vector3d'类型的左值"
我用的时候:
const Vector3d &GetPosition(void) const
{
return static_cast<const Vector3d &>(*this);
}
Run Code Online (Sandbox Code Playgroud)
事情编译好,但我不能以我想要的方式使用它:
Trajectory t;
t.Position=Set(20,30,50);
Run Code Online (Sandbox Code Playgroud)
因为t.Position是const,因此是一个不合适的左值,正如编译器宣布的那样.
关于如何将基类引入非常量解除引用的任何想法?