C 继承,调用给定类功能而不是其父
C++ inheritance, calling the given classes function instead of its parent?
真的很糟糕的标题,无法想到如何言语,对不起。
所以说我有以下代码:
class A {
virtual int getSize() {
return 0;
}
}
class B : public A {
int getSize() {
return 32;
}
}
void doStuff(A a) {
std::cout << a.getSize() << std::endl;
}
int main() {
B b;
doStuff(b);
}
它将打印出0
,但是我希望它打印出32
。换句话说,我想将其通过类,然后打印出该类功能,因此我可以创建一个C
,其中大小为64,如果我将该C实例传递给doStuff
函数,我希望它可以打印64。
有什么办法可以在C 中执行此操作?
一个字节补丁:
void doStuff(A &a) {
std::cout << a.getSize() << std::endl;
}
您的版本按值进行参数,这意味着该函数制作了b
的副本(A
的副本),然后调用该副本的getSize()
。在此版本中,该函数通过参考获取参数,并调用b
的getSize()
,即B::getSize()
。
您应该使用指针,甚至更好:智能指针!这样,调用运行时类型的功能。这是多词主义的基本例子。如果您想避免指针,Beta的切片方法同样有效。
#include <iostream>
#include <memory>
class A {
virtual int getSize() {
return 0;
}
}
class B : public A {
virtual int getSize() {
return 32;
}
}
void doStuff(std::shared_ptr<A> a) {
std::cout << a->getSize() << std::endl;
}
int main() {
std::shared_ptr<A> b(new B());
doStuff(b); // Will output '32'.
}
这应该正确调用b。
切片对象是一种方法,此外,我认为您认为您在C 中非常直接地使用多态性。http://www.cplusplus.com/doc/tutorial/polymorphism/
这几乎是立即适用的,只需称您的班级形状,B和C可能是正方形和三角形。您的dostuff函数可以将指针置于形状,然后可以将其传递给三角形或正方形,当您尊重该功能中的形状时,它将调用正确的函数。
所以您将拥有(我认为您需要公开会员):
class A {
public:
virtual int getSize() {
return 0;
}
};
class B : public A {
public:
int getSize() {
return 32;
}
};
void doStuff(A* a) {
std::cout << a->getSize() << std::endl;
}
int main() {
B b;
doStuff(&b);
}
相关文章:
- C++继承和相同的功能名称
- 有没有办法C++将给定类的功能限制为仅另一个类(不使用继承,朋友)?
- C++17 'inline variable' vs 'extern' 关键字继承自 C 的新功能
- 为什么虚拟继承即使不涉及虚拟功能也需要 vtable?
- 抽象类 A 由类 C 继承"through"类 B "intermediary"。如何声明虚拟功能?
- 使用继承和虚拟功能应用五个规则
- 继承多态性功能调用
- C++继承 - 覆盖功能,包括使用 "::" s、.h 文件和.cpp文件
- GCC称将功能与多个继承过载时,称其为模棱两可,但Clang和MSVC没有
- C 从同一基本模板类覆盖功能,具有多个继承模棱两可的函数调用
- 有关继承层次结构的问题,没有任何虚拟功能
- C 继承问题错误C2084功能已经具有主体
- 朋友功能是否继承?为什么基类朋友功能在派生的类对象上工作
- 对具有继承功能的结构使用初始值设定项列表
- 继承和虚拟功能
- 继承:从基类调用派生的类功能
- 在C 中继承类功能:一般问题,以更好地理解,如果有人可以指出我的错误
- 需要有关多个继承和可选功能覆盖C 的建议
- 朋友功能和继承在CPP中
- 继承和功能