[英]C++ Abstract class pointer in method
So I have a c++ project that I'm working on and I'm trying to understand an other guys code but all I get are errors and confusion about c++ abstract classes.所以我有一个c++项目,我正在研究,我试图理解其他人的代码,但我得到的只是关于 c++ 抽象类的错误和困惑。
So What I have is a header file a cpp file and a main program.所以我有一个 header 文件一个 cpp 文件和一个主程序。
I want to create an abstract class pointer and then pass it to a method that initializes it to a subclass and then back in the main program I can use it as the subclass:我想创建一个抽象的 class 指针,然后将其传递给将其初始化为子类的方法,然后返回到主程序中,我可以将其用作子类:
main.cpp:主.cpp:
#include "a.h"
#include <iostream>
using namespace std;
void parse(A* a){
a = new B();
a->foo();
}
int main() {
A* a;
parse(a);
a->foo();
}
ah:啊:
class A{
public:
virtual void foo() const = 0;
virtual ~A(){ }
};
class B : public A{
public:
void foo() const override;
};
class C : public A{
public:
void foo() const override;
};
a.cpp a.cpp
#include <iostream>
#include "a.h"
void B::foo() const{
std::cout << "B" << std::endl;
}
void C::foo() const{
std::cout << "C" << std::endl;
}
Basically here I think I should cee a B but I get a segmentation error or the program exits without printing anything.基本上在这里,我认为我应该 cee 一个 B 但我得到一个分段错误或程序退出而不打印任何东西。
Thank you for your help!谢谢您的帮助!
In main you have uninitialized pointer a
在 main 中,您有未初始化的指针a
int main() {
A* a;
parse(a);
a->foo();
}
So this statement所以这个说法
a->foo();
results in undefined behavior.导致未定义的行为。
As for the function parse至于 function 解析
void parse(A* a){
a = new B();
a->foo();
}
then it deals with its local variable a
.然后它处理它的局部变量a
。 Changing the local variable does not affect the original pointer declared in main.更改局部变量不会影响 main 中声明的原始指针。
You need to declare the parameter as having a referenced type您需要将参数声明为具有引用类型
void parse(A* &a){
a = new B();
a->foo();
}
In this case the pointer a declared in main will be passed to the function by reference and the function will change the original pointer a.在这种情况下,main 中声明的指针 a 将通过引用传递给 function,而 function 将更改原始指针 a。
Besides the issue of undefined behviour described in Vlad's answer , your example also leaks memory, even if the pointer in main
was correctly initialised.除了弗拉德的回答中描述的未定义行为问题外,即使main
中的指针已正确初始化,您的示例也会泄漏 memory。
I recommend an alternative solution.我推荐一个替代解决方案。 Instead of modifying the pointer through a reference, I recommend to not use owning bare pointers.我建议不要使用拥有裸指针,而不是通过引用修改指针。 Instead, return the pointer, and use a smart pointer for ownership:相反,返回指针,并使用智能指针作为所有权:
std::unique_ptr<A>
parse(){
auto a = std::make_unique<B>;
a->foo();
return a;
}
int
main() {
auto a = parse();
a->foo();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.