ZBLOG

friend与final

在C++中,friendfinal是两个不同的关键字,它们有各自的用途和意义。下面将对这两个关键字进行详细解释。

1. friend

  • 用途friend关键字用于指定某个类或函数可以访问另一个类的私有成员和保护成员。
  • 特性
    • 声明为友元的函数或类可以直接访问该类的私有和保护成员。
    • friend关系不是继承关系,即使某个类是另一个类的友元,也不会影响继承关系。

示例代码

#include <iostream>

class ClassB; // 前向声明

class ClassA {
private:
    int secret;

public:
    ClassA() : secret(42) {}

    // Friend declaration
    friend void revealSecret(ClassB& b);
};

class ClassB {
public:
    void showSecret(ClassA& a) {
        std::cout << "ClassB accessing ClassA's secret: " << a.secret << std::endl;
    }
};

// Function that is a friend of ClassA
void revealSecret(ClassB& b) {
    std::cout << "Revealing secret from ClassA: " << b.secret << std::endl;
}

int main() {
    ClassA a;
    ClassB b;

    b.showSecret(a);   // Accessing private member through friend function

    return 0;
}

2. final

  • 用途final关键字用于阻止继承或重写虚拟函数。它可以应用于类和虚拟函数。
  • 特性
    • 如果一个类被标记为final,则无法从该类派生新的子类。
    • 如果一个虚拟函数被标记为final,则子类不能重写这个虚拟函数。

示例代码

#include <iostream>

class Base {
public:
    virtual void display() { 
        std::cout << "Base display" << std::endl; 
    }
};

// Final class, cannot be inherited
class Derived final : public Base {
public:
    void display() override { 
        std::cout << "Derived display" << std::endl; 
    }
};

// Uncommenting the following line will cause a compilation error
// class FurtherDerived : public Derived {};

int main() {
    Base* basePtr = new Derived();
    basePtr->display(); // Calls Derived's display

    delete basePtr;
    
	return 0;
}

总结

  • friend: 用于提供访问权限,使得特定的外部函数或类能够访问当前类的私有和受保护成员。

  • final: 用于防止进一步的继承或防止覆盖虚拟函数,以确保不再改变基类或基于它的新实现。这对于设计API时很有用,可以明确表示哪些部分不应该被修改。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=19911

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?