基类方法别名
Base class method alias
让我们考虑以下代码:
#include <iostream>
class Base
{
public:
void foo() //Here we have some method called foo.
{
std::cout << "Base::foo()n";
}
};
class Derived : public Base
{
public:
void foo() //Here we override the Base::foo() with Derived::foo()
{
std::cout << "Derived::foo()n";
}
};
int main()
{
Base *base1 = new Base;
Derived *der1 = new Derived;
base1->foo(); //Prints "Base::foo()"
der1->foo(); //Prints "Derived::foo()"
}
如果我有上述的类,我可以从Base
或Derived
类实例中的任何一个调用foo
方法,这取决于我需要什么::foo()
。但是存在某种问题:如果我需要Derived
类实例,但我确实需要从该实例调用Base::foo()
方法,该怎么办?
这个问题的解决可能是下一步:我将下一个方法粘贴到派生类
public:
void fooBase()
{
Base::foo();
}
当我需要派生类实例中的CCD_ 8方法时,调用CCD_。
问题是,我能用using
指令这样做吗
using Base::foo=fooBase; //I know this would not compile.
der1->Base::foo(); //Prints "Base::foo()"
您可以使用范围解析来调用基类方法,以指定函数版本并解决歧义,这在您不想使用默认解析时很有用。
类似的(不完全相同的情况)例子被提到@cppreference
struct B { virtual void foo(); }; struct D : B { void foo() override; }; int main() { D x; B& b = x; b.foo(); // calls D::foo (virtual dispatch) b.B::foo(); // calls B::foo (static dispatch) }
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- 从基类实例调用派生类方法而不进行强制转换
- 函数从唯一代码调用正确的子类方法
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- 类方法和全局函数中的别名
- 基类方法别名