gpt4 book ai didi

c++ - 在 base 中使用抽象期望它是派生类?

转载 作者:搜寻专家 更新时间:2023-10-31 00:23:03 24 4
gpt4 key购买 nike

使用这个简单的代码:

class A{ 
public:
virtual void foo() = 0;
void x(){ foo(); }
};
class B: public A{ foo(){ ... } };

main(){
B b;
b.x();
}

我想要的是构建一个抽象类,该类将具有一个函数,该函数将调用一个期望它在派生类中实现的函数

问题是我似乎无法完成这项工作,编译器说它无法编译,因为它找不到要在 x( ) 的基类。这行得通吗?谁能给我举个例子?

编辑:似乎它只是在“foo();”时不起作用在 A 类(基础类)的析构函数中...
这让我很困惑。 =[

EDIT2:这变得多么有趣。我刚刚创建了一个 callfoo(){ foo();现在它编译正常了,但是如果我尝试直接从基类 A 的析构函数中调用纯抽象函数,它会给我错误……很奇怪。有人对此有任何想法吗? O_o

请问有什么帮助吗?

谢谢,
乔纳森

更新

它在析构函数之外工作。现在我只是感到困惑。

尝试将“foo()”放入 A(base) 类的析构函数中,至少对我来说不是编译...

有什么帮助吗?

最佳答案

没有什么能阻止你这样做:

struct A {
virtual ~A() {}
virtual void f() = 0;
virtual void g() { f(); }
};

struct B : A {
void f() { std::cout << "B::f()" << std::endl; }
};

// ...
A* a = new B;
a->g(); // prints "B::f()"

至于从析构函数(或构造函数)调用纯虚函数:不要!它会调用未定义的行为。

§10.4/6:

Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.

关于c++ - 在 base 中使用抽象期望它是派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2576368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com