Resolve ambiguity in inheritance When there is a function with the same name, you can resolve the ambiguity by using the following method: use the scope resolver (::) to specify the class to which the function belongs. Override base class functions in derived classes. Create a base class pointer to the derived class object and then use the pointer to call the base class function.
When base class and derived class When a class has a function with the same name, ambiguity will arise when calling the function in a derived class. This is because the compiler cannot determine which function version to call.
There are several ways to resolve ambiguities in inheritance:
Use the scope resolver: Use the scope resolver (::
) to specify the class to which the function to be called belongs.
class Base { public: void func() { std::cout << "Base::func()" << std::endl; } }; class Derived : public Base { public: void func() { std::cout << "Derived::func()" << std::endl; } void callBaseFunc() { Base::func(); // 使用作用域解析符调用基类函数 } };
Override base class function: Override base class function in derived class.
class Base { public: virtual void func() { std::cout << "Base::func()" << std::endl; } }; class Derived : public Base { public: void func() override { std::cout << "Derived::func()" << std::endl; } };
Use base class pointer: Create a base class pointer and point to the derived class object. Then, use the pointer to call the base class function.
class Base { public: void func() { std::cout << "Base::func()" << std::endl; } }; class Derived : public Base { public: void func() { std::cout << "Derived::func()" << std::endl; } }; int main() { Base* basePtr = new Derived; basePtr->func(); // 调用基类函数 return 0; }
Consider the following code:
class Animal { public: void speak() { std::cout << "Animal speaks" << std::endl; } }; class Dog : public Animal { public: void speak() { std::cout << "Dog barks" << std::endl; } }; class Cat : public Animal { public: void speak() { std::cout << "Cat meows" << std::endl; } }; int main() { Animal* animal = new Dog; // 创建指向 Dog 对象的 Animal 指针 animal->speak(); // 调用 Dog::speak() animal = new Cat; // 创建指向 Cat 对象的 Animal 指针 animal->speak(); // 调用 Cat::speak() return 0; }
In this example, using a base class pointer can solve the ambiguity problem. We can access specific functions of different derived classes without any explicit modification to the code.
Understanding ambiguity in inheritance and knowing how to resolve it is critical to writing robust and maintainable C code. By using the techniques given, you can easily handle ambiguities and ensure that the correct function is called.
The above is the detailed content of Detailed explanation of C++ function inheritance: How to deal with ambiguities in inheritance?. For more information, please follow other related articles on the PHP Chinese website!