Return types of virtual functions

本文探讨了C++中虚拟函数的协变返回类型特性。通常情况下,派生类中覆盖的虚拟函数必须与基类中的虚拟函数具有相同的返回类型。但当返回类型为指向类的指针或引用时,则允许返回派生类的指针或引用。

Under normal circumstances, the return type of a virtual function and it’s override must match. Thus, the following will not work:

classBase
{
public:
    virtualint GetValue() { return5; }
};
 
class Derived: public Base
{
public:
    virtual double GetValue() { return6.78; }
};

However, there is one special case in which this is not true. If the return type of a virtual function is a pointer or a reference to a class, override functions can return a pointer or a reference to a derived class.These are called covariant return types. Here is an example:

class Base
{
public:
    // This version of GetThis() returns a pointer to a Base class
    virtual Base* GetThis() { return this; }
};
 
class Derived: public Base
{
    // Normally override functions have to return objects of the same type as the base function
    // However, because Derived is derived from Base, it's okay to return Derived* instead of Base*
    virtual Derived* GetThis() { return this; }
};

Note that some older compilers (eg. Visual Studio 6) do not support covariant return types.

Network resource definitions of iLO 5 v3.04 For each data type provided by the HPE ilO Redfish service, find below its description including the list of possible instances (URIs), links to related other resources, described properties and many other details. Refer to the data types and collection section for more information on Redfish data types and collections. NetworkAdapterCollection @odata.type: "#NetworkAdapterCollection.NetworkAdapterCollection" A Collection of NetworkAdapter resource instances. Resource Instances Uri HTTP Allow /redfish/v1/chassis/{item}/networkadapters GET Links to other Resources Link Name Destination type Members[] NetworkAdapter Members (array) Member of NetworkAdapterCollection.NetworkAdapterCollection Members is an array containing elements of: Members[{item}].@odata.id Member of NetworkAdapterCollection.NetworkAdapterCollection Type string Read Only True Format uri-reference Members@odata.count Member of NetworkAdapterCollection.NetworkAdapterCollection Description The total number of collection members. Type integer Read Only True Oem.Hpe.MemberContents Member of NetworkAdapterCollection.NetworkAdapterCollection Description Provides the discovery status of this collection. For some server platforms, only partial device discovery is possible under auxiliary power. Type string or null Read Only True Added iLO 5 1.40 The following are the supported values: Value Description Null A value is temporarily unavailable AllDevices The server state allows complete device discovery. All installed devices are listed as members. AuxPowerDevices The server architecture may not support power to all installed devices in the current auxiliary power state. Only devices capable of operating in this power state are listed as members. Additional devices may be listed when the server is fully powered. NetworkAdapter @odata.type: "#NetworkAdapter.v1_5_0.NetworkAdapter" A NetworkAdapter represents the physical network adapter capable of connecting to a computer network. Examples include but are not limited to Ethernet, Fibre Channel, and converged network adapters. The Data Source is either DCi or RDE. HPE OEM section shall be present only for DCi Data Source. Resource Instances Uri HTTP Allow /redfish/v1/chassis/{item}/networkadapters/{item} GET POST PATCH /redfish/v1/chassis/{item}/networkadapters/{item}/settings GET POST PATCH @Redfish.Settings Member of NetworkAdapter.v1_5_0.NetworkAdapter See the Redfish standard schema and specification for information on common @Redfish properties. Controllers (array) Member of NetworkAdapter.v1_5_0.NetworkAdapter Controllers is an array containing elements of: Controllers[{item}].ControllerCapabilities Controllers[{item}].ControllerCapabilities.DataCenterBridging Controllers[{item}].ControllerCapabilities.DataCenterBridging.Capable Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The value of this property shall be a boolean indicating whether this controller is capable of Data Center Bridging (DCB). Type boolean or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.NPAR Controllers[{item}].ControllerCapabilities.NPAR.NparCapable Member of NetworkAdapter.v1_5_0.NetworkAdapter Description Indicates whether or not NIC function partitioning is supported by a controller. Type boolean or null Read Only True Added iLO 5 1.40 Controllers[{item}].ControllerCapabilities.NPAR.NparEnabled Member of NetworkAdapter.v1_5_0.NetworkAdapter Description When true, NIC function partitioning is active on this controller. Type boolean or null Read Only False Added iLO 5 1.40 Controllers[{item}].ControllerCapabilities.NPIV Controllers[{item}].ControllerCapabilities.NPIV.MaxDeviceLogins Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The maximum number of N_Port ID Virtualization (NPIV) logins allowed simultaneously from all ports on this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.NPIV.MaxPortLogins Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The maximum number of N_Port ID Virtualization (NPIV) logins allowed per physical port on this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.NetworkDeviceFunctionCount Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The maximum number of physical functions available on this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.NetworkPortCount Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The number of physical ports on this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.VirtualizationOffload Controllers[{item}].ControllerCapabilities.VirtualizationOffload.SRIOV Controllers[{item}].ControllerCapabilities.VirtualizationOffload.SRIOV.SRIOVVEPACapable Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The value of this property shall be a boolean indicating whether this controller supports Single Root Input/Output Virtualization (SR-IOV) in Virtual Ethernet Port Aggregator (VEPA) mode. Type boolean or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.VirtualizationOffload.VirtualFunction Controllers[{item}].ControllerCapabilities.VirtualizationOffload.VirtualFunction.DeviceMaxCount Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The maximum number of Virtual Functions (VFs) supported by this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.VirtualizationOffload.VirtualFunction.MinAssignmentGroupSize Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The minimum number of Virtual Functions (VFs) that can be allocated or moved between physical functions for this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].ControllerCapabilities.VirtualizationOffload.VirtualFunction.NetworkPortMaxCount Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The maximum number of Virtual Functions (VFs) supported per network port for this controller. Type number or null Read Only True Added iLO 5 1.20 Controllers[{item}].FirmwarePackageVersion Member of NetworkAdapter.v1_5_0.NetworkAdapter Description The version number of the user-facing firmware package. Type string or null Read Only True Added iLO 5 1.20 Controllers[{item}].Links Controllers[{item}].Links.NetworkDeviceFunctions (array) Member of NetworkAdapter.v1_5_0.NetworkAdapter NetworkDeviceFunctions is an array containing elements of: NetworkDeviceFunctions[{item}].@odata.id Member of NetworkAdapter.v1_5_0.NetworkAdapter 请学习HP官网的文档,然后再去给我取物理网卡名称
最新发布
09-25
/** * @file KWidget.h * @brief Declaration of the base GUI widget class * @author(ma.ji@kotei.com.cn) * @version 0.1 * @date 2025-06-16 * * @copyright Copyright (c) 2025 */ #pragma once #include <vector> #include <memory> #include "KGuiObject.h" const uint32_t kConstMaxScreenWidth = 2560U; const uint32_t kConstMaxScreenHeight = 1440U; /** * @enum eDrawMode * @brief Defines how the background image should be drawn. */ enum class eDrawMode { kOriginal, ///< Usesing the original size of the image to fill the widget. kStretch, ///< Stretch the image to fill the widget. }; /** * @enum eWindowStyle * @brief Enumerates different types of GUI window components. */ enum class eWindowStyle : uint32_t { kGuiWidget, ///< Generic container widget (e.g., KWidget) kGuiDialog, ///< modal dialog widget that blocks input to other widgets when shown kGuiCheckButton, ///< Clickable button (e.g., KCheckButton) kGuiToggleButton, ///< Clickable button (e.g., KToggleButton) kGuiExclusiveGroup, ///< Exclusive selection group (e.g., ExclusiveSelectionGroup) kGuiMultiLabel, ///< Label widget supporting multiple foreground images with different states kGuiComposite, ///< Composite window container with child management widget kEllipseTracker, ///< tracking along an ellipse widget kGuiCustom ///< User-defined window type }; /** * @class KWidget * @brief Base class for all user interface components * KWidget represents a rectangular area in a GUI system, handling user input, * rendering, and layout management. It implements parent-child relationships * and basic event handling mechanisms. * @note Derived classes must implement pure virtual functions for specific behavior. * @see none */ class KWidget : public KGuiObject { // Give an alias to the callback function that notify gui event using EventCallback = std::function<void(KGuiEvent *)>; public: /** * @brief Construct a widget with optional parent * @param parent Parent widget (nullptr for top-level) * @param style widget style * @return none * @note none * @see none */ explicit KWidget(KWidget* parent = nullptr, eWindowStyle style = eWindowStyle::kGuiWidget); /** * @brief Virtual destructor ensuring proper cleanup * @return none * @note Automatically removes itself from parent's children list * and deletes all child widgets * Do not use smart pointers when creating widget * @see none */ virtual ~KWidget(); // Prohibit copying KWidget(const KWidget&) = delete; KWidget& operator=(const KWidget&) = delete; public: /** * @brief Sets or updates the ID for widget * @param id Unique integer identifier for the window * @return none * @note none * @see none */ virtual void setWindowId(uint32_t id); /** * @brief Retrieves the ID of a specific window * @return Optional containing the window ID if found * @note none * @see setWindowId */ virtual uint32_t getWindowId() const; /** * @brief Sets theme definitions * @param style The style of theme enumeration value * @return none * @note none * @see none */ virtual void setSkinThemes(const uint32_t& style); /** * @brief Gets theme definitions * @param style The style of theme enumeration value * @return Number of the current loaded skin themes * @note none * @see none */ virtual uint32_t skinThemes() const; /** * @brief Register a event notify callback function. * @param callback The callback function that is finally executed. * @return none * @note none * @see none */ void registerEvent(EventCallback callback); /** * @brief Widget visibility state * @return Return the widget's visibility state. true if it is visible, otherwise return false. * @note none * @see none */ virtual bool isVisible() const override; /** * @brief Sets Widget visibility * @param visible widget visibility state * @return none * @note none * @see none */ virtual void setVisible(bool visible) override; /** * @brief Sets Widget show * @return none * @note none * @see none */ virtual void show() override; /** * @brief Sets Widget hide * @return none * @note none * @see none */ virtual void hide() override; /** * @brief Widget enabled state * @return Return the widget's enabled state. return true ff it is enabled, otherwise return false. * @note none * @see none */ virtual bool isEnabled() const override; /** * @brief Sets Widget enabled state * @return none * @note none * @see none */ virtual void setEnabled(bool enabled) override; /** * @brief Checks if point is within Widget boundaries * @param p Point to test * @return true if point is inside Widget * @note none * @see none */ virtual bool contains(const KPoint& p) const override; /** * @brief Process a GUI event in the current context. * @param e Pointer to the KGuiEvent object describing the event details. * The caller retains ownership of the event object. * @return true if the event was fully handled and should not propagate further, otherwise return false. * @note none * @see KGuiEvent */ virtual void onEvent(KGuiEvent *e) override; /** * @brief Set the widget's geometry * @param x Horizontal position relative to parent * @param y Vertical position relative to parent * @param width Width in pixels * @param height Height in pixels * @return none * @note none * @see none */ virtual void setGeometry(int x, int y, int width, int height) override; /** * @brief Move widget to new position * @param x New horizontal position * @param y New vertical position * @return none * @note none * @see none */ virtual void move(int x, int y); /** * @brief Resize widget dimensions * @param width New width in pixels * @param height New height in pixels * @return none * @note none * @see none */ virtual void resize(int width, int height); /** * @brief Get widget geometry parameters * @return KRectangle containing (x, y, width, height) * @note none * @see none */ virtual KRectangle geometry() const; /** * @brief Sets the background image id. * @param image id to the image. * @return none * @note none * @see none */ void setBackgroundImage(const uint32_t image); /** * @brief Sets the background draw mode. * @param mode Drawing mode (Original/Stretch). * @return none * @note none * @see none */ void setDrawMode(eDrawMode mode); /** * @brief Gets the current background draw mode. * @return Active draw mode. * @note none * @see none */ eDrawMode getDrawMode() const; /** * @brief Gets the current windows style. * @return window style mode. * @note none * @see eWindowStyle */ eWindowStyle getWindowStyle() const; public: /** * @brief Set parent widget * @param parent New parent widget (nullptr removes parent) * @return none * @note none * @see none */ void setParent(KWidget* parent); /** * @brief Requests that the child container capacity be at least enough to contain a specified number of elements. * @param n Minimum capacity requested (in terms of number of elements). * @return none * @note none * @see capacity(), shrink_to_fit() */ void setChildReserve(uint32_t n); /** * @brief Get current parent widget * @return Pointer to parent widget * @note none * @see none */ KWidget* parent() const noexcept; /** * @brief Get list of child widgets * @return Const reference to children collection * @note none * @see none */ const std::vector<KWidget*>& children() const noexcept; /** * @brief Adds a child widget to the current widget. * @param child The child widget to add. Must be a valid KWidget instance. * @return none * @note If the child already exists in the current widget, no action is taken. * @see none. */ void addChild(KWidget* childs); /** * @brief Removes a child widget from the current widget. * @param child The child widget to remove. * @return none * @note If the child is not found, no action is taken. * @see none */ void removeChild(KWidget* childs); /** * @brief Clear all child from the group * @return none * @note none * @see none */ void clearChildren(); /** * @brief Called when window needs repaint by outside * @param pen Affected screen pen * @return none * @note none * @see none */ virtual void paintEvent(KPen pen) override; /** * @brief Called on mouse press * @param x Mouse X coordinate * @param y Mouse Y coordinate * @return true if point is within geometry area, false otherwise * @note none * @see none */ virtual bool mousePressEvent(int x, int y) override; /** * @brief Called on mouse press * @param pos Mouse Pressed (X, Y)coordinate * @return true if point is within geometry area, false otherwise * @note none * @see none */ virtual bool mousePressEvent(const KPoint &pos) override; /** * @brief Called on mouse release * @param x Mouse X coordinate * @param y Mouse Y coordinate * @return true if point is within geometry area, false otherwise * @note none * @see none */ virtual bool mouseReleaseEvent(int x, int y) override; /** * @brief Called on mouse release * @param pos Mouse release (X, Y)coordinate * @return true if point is within geometry area, false otherwise * @note none * @see none */ virtual bool mouseReleaseEvent(const KPoint &pos) override; /** * @brief Called on mouse move * @param pos Mouse move (X, Y)coordinate * @return true if widget is currently in the state where the mouse press has been triggered, false otherwise * @note none * @see none */ virtual bool mouseMoveEvent(const KPoint &pos) override; /** * @brief Resize event handler * @param event Resize event * @return none * @note none * @see none */ virtual void resizeEvent(KGuiEvent* event) override; /** * @brief Check whether the widget is being pressed * @param event Resize event * @return Return true if is pressed, otherwise return false. * @note none * @see none */ inline bool isPressed() const { return m_pressed;} protected: /** * @brief Updates the layout of the widget and its children. * @return none * @note none. * @see none */ void updateGeometry(); protected: /** * @brief Called repaint by KWidget inside triggered. * @param pen Affected screen pen * @param image image resource id * @return none * @note none * @see none */ virtual void renderer(KPen pen, const uint32_t &image); private: bool m_visible; ///< Storge widget visibility property bool m_enabled; ///< Storge widget enable property KPoint m_position; ///< Widget position (top-left corner) KSize m_size; ///< Widget dimensions (width/height) #if defined(__QNXNTO__) IVSAVMViewPortAndViewInfo m_geometry; #endif protected: KWidget* m_pressedWidget; ///< Storge pressed child widget KWidget* m_parent; ///< Parent widget relationships std::vector<KWidget*> m_children; ///< child widget relationships eDrawMode m_draw_mode; ///< Storge image rendering mode eWindowStyle m_window_style; ///< Storge window style KSignalObject<KGuiEvent*> m_trigger; ///< Define widget base event handler EventCallback m_callback; ///< event notify callback function. uint32_t m_windowId; ///< Storge widget identifier ID uint32_t m_image; ///< Storge widget background image id. uint32_t m_skin_style; ///< Storge current skin type bool m_pressed; ///< Pressed state }; 写测试用例
08-20
Create an inheritance hierarchy that a bank might use to represent customers’ bank accounts. All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit) money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e., credit or debit). Create an inheritance hierarchy containing base class Account and derived classes SavingsAccount and CheckingAccount that inherit from class Account. Base class Account should include one data member of type double to represent the account balance. The class should provide a constructor that receives an initial balance and uses it to initialize the data member. The constructor should validate the initial balance to ensure that it is greater than or equal to 0.0. If not, the balance should be set to 0.0 and the constructor should display an error message, indicating that the initial balance was invalid. The class should provide three member functions. Member function credit should add an amount to the current balance. Member function debit should withdraw money from the Account and ensure that the debit amount does not exceed the Account’s balance. If it does, the balance should be left unchanged and the function should print the message "Debit amount exceeded account balance." Member function getBalance should return the current balance. Derived class SavingsAccount should inherit the functionality of an Account, but also include a data member of type double indicating the interest rate (percentage) assigned to the Account. SavingsAccount’s constructor should receive the initial balance, as well as an initial value for the SavingsAccount’s interest rate. SavingsAccount should provide a public member function calculateInterest that returns a double indicating the amount of interest earned by an account. Member function calculateInterest should determine this amount by multiplying the interest rate by the account balance. [Note: SavingsAccount should inherit member functions credit and debit as is without redefining them.] Derived class CheckingAccount should inherit from base class Account and include an additional data member of type double that represents the fee charged per transaction. CheckingAccount’s constructor should receive the initial balance, as well as a parameter indicating a fee amount. Class CheckingAccount should redefine member functions credit and debit so that they subtract the fee from the account balance whenever either transaction is performed successfully. CheckingAccount’s versions of these functions should invoke the base-class Account version to perform the updates to an account balance. CheckingAccount’s debit function should charge a fee only if money is actually withdrawn (i.e., the debit amount does not exceed the account balance). [Hint: Define Account’s debit function so that it returns a bool indicating whether money was withdrawn. Then use the return value to determine whether a fee should be charged.] After defining the classes in this hierarchy, write a program that creates objects of each class and tests their member functions. Add interest to the SavingsAccount object by first invoking its calculateInterest function, then passing the returned interest amount to the object’s credit function.
05-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值