我面临一个奇怪的问题。我编写了一个 Parent 抽象类(实现纯虚拟 test() 方法)及其 Child 类(实现 test() 方法)。
class Parent
{
public :
Parent();
virtual ~Parent() = default;
virtual bool test() const = 0;
};
class Child : public Parent
{
public :
bool test() const;
};
Run Code Online (Sandbox Code Playgroud)
然后,我编写了一个“Grid”类,它应该包含指向 Parent 的指针的二维数组。该数组是使用向量库完成的:“_cells”是指向 Parent 的指针的宽度*高度向量。_cells 在 Grid 对象构造期间使用动态分配进行填充,并在析构函数中释放。Operator() (int a, int b) 被重载,以便能够使用以下模式调用 Parent 对象:myGrid(x,y)。
class Grid
{
int _w, _h;
std::vector<Parent*> _cells;
public :
Grid(int w = 0, int h = 0);
~Grid();
Parent* &operator()(int x, int y);
private :
void …Run Code Online (Sandbox Code Playgroud) c++ pure-virtual segmentation-fault dynamic-allocation c++11
在这种特殊情况下,为什么我必须在基类中定义非纯虚方法以避免链接器错误?
这会产生链接器错误:
class A
{
public:
virtual ~A(){}
virtual void foo() = 0;
virtual void bar();
};
class B : public A
{
public:
void foo()
{
}
void bar()
{
}
};
int main()
{
B b;
}
Run Code Online (Sandbox Code Playgroud)
输出:
/tmp/cc5E8Tit.o: In function `A::~A()':
:(.text._ZN1AD2Ev[_ZN1AD5Ev]+0x13): undefined reference to `vtable for
A' /tmp/cc5E8Tit.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference
to `typeinfo for A' collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
但如果我在类中定义 bar 方法,A它链接正常:
class A
{
public:
virtual ~A(){}
virtual void foo() = …Run Code Online (Sandbox Code Playgroud) 有一个默认的复制构造函数/赋值运算符可以执行浅复制。即使是抽象类,它们也是默认创建的吗?
我显然不会'克服'C++.
在这个编程任务中,我已经走到了尽头.此代码行发生运行时错误:
else if (grid[i][j]->getType() == WILDEBEEST) { ...
Run Code Online (Sandbox Code Playgroud)
消息"运行时错误 - 纯虚函数调用".
根据我的理解,如果函数引用尝试在当前未实例化子类时调用(虚拟)基类,则会发生此错误.但是,我没有看到我犯了这个错误.
相关守则:
教授守则:
const int LION = 1;
const int WILDEBEEST = 2;
//
// .
// .
// .
//
class Animal {
friend class Savanna; // Allow savanna to affect animal
public:
Animal();
Animal(Savanna *, int, int);
~Animal();
virtual void breed() = 0; // Breeding implementation
virtual void move() = 0; // Move the animal, with appropriate behavior
virtual int getType() = 0; // Return if …Run Code Online (Sandbox Code Playgroud) 考虑派生类的基类,其中基类应该为其所有派生提供一些(多态)方法,例如armithmetic或bitweise重载运算符.派生类不应修改此操作以确保正确执行.但是,与此同时,我想进行评估 - 在我的示例中函数isError() - 运算符必须是子类和纯虚拟的,因此必须定义:
class Mom
{
public:
virtual bool operator && (const Mom&) const final
{
return this->isError() && p_rOther.isError();
}
private:
virtual bool isError() = 0;
};
Run Code Online (Sandbox Code Playgroud)
鉴于当前标准,似乎不允许这样做,因为"纯虚拟性"意味着子类必须实现基类的所有虚函数,而"final"关键字与此范例相矛盾.
任何建议或想法如何处理这个矛盾?
我刚刚意识到我过多地简化了代码并且它没有反映我真正的问题.我为不具体而道歉.我实际上要做的是以下内容:
在线演示:
#include<iostream>
class A
{
public:
A();
virtual void f()= 0;
void g();
};
A::A()
{
g();
}
void A::g()
{
f();
}
class B : public A
{
public:
B() {};
void f() {};
};
int main()
{
B b;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想程序调用纯虚函数,A::f因为B在调用构造函数时尚未创建.
这是正确的,我该如何克服这个问题?
请原谅我早些时候提出过于简化的问题.
c++ ×6
pure-virtual ×6
c++11 ×2
constructor ×1
final ×1
inheritance ×1
overriding ×1
runtime ×1