You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cat类代码中创建友元函数以打印对象的年龄与易怒值

给Cat类添加友元函数实现年龄和易怒值打印

要实现需求,分两步修改代码:

1. 在Cat类中声明友元函数

在类的声明里(推荐放在public区域),用friend关键字声明要创建的友元函数,让它获得访问类私有成员的权限:

class Cat
{
    private :
        std :: string name ;
        int age ;
        float irascibility ;
    public :
    // 原有成员函数保持不变...
    
    // 声明友元函数
    friend void printCatInfo(const Cat& cat);
};

2. 在类外部定义友元函数

友元函数不属于类的成员,所以定义时不需要加Cat::前缀,直接实现打印逻辑:

#include <iostream> // 需要引入iostream用于输出

void printCatInfo(const Cat& cat)
{
    std::cout << "猫咪年龄:" << cat.age << std::endl;
    std::cout << "猫咪易怒值:" << cat.irascibility << std::endl;
}

完整示例代码

修改后的头文件Cat.h:

#ifndef CAT_H // 修正原代码宏定义的拼写错误
#define CAT_H

#include <string>

class Cat
{
    private :
        std :: string name ;
        int age ;
        float irascibility ;
    public :
    void setName(std :: string n) {name = n;}
    std :: string getName ( ) {return name ; }
    void setAge(int a) {age = a;}
    int getAge( ) {return age ;}
    void setIrascibility (float i) {irascibility = i;}
    float getIrascibility ( ){return irascibility;}
    
    std :: string meow(int rep)
    {
        std :: string output = " " ;
        for (int i { 0 } ; i < rep - 1 ; i++) // 修正全角减号为半角
            output += "MEOW" ;
        if ( rep != 0 )
            output += "MEOW" ;
        return output ;
    }

    // 声明友元函数
    friend void printCatInfo(const Cat& cat);

};

#endif

测试用的主函数示例:

#include "Cat.h"
#include <iostream>

void printCatInfo(const Cat& cat)
{
    std::cout << "猫咪年龄:" << cat.age << std::endl;
    std::cout << "猫咪易怒值:" << cat.irascibility << std::endl;
}

int main()
{
    Cat myCat;
    myCat.setAge(3);
    myCat.setIrascibility(0.7f);
    printCatInfo(myCat);
    return 0;
}

关键说明

  • 友元函数通过friend声明获得访问类私有/保护成员的权限,无需调用getter方法就能直接读取age和irascibility。
  • 用const Cat&作为参数,既避免拷贝对象的开销,又保证函数不会修改传入的Cat对象。
  • 修正了原代码里的两处小问题:头文件保护宏的拼写错误、循环条件里的全角减号。

内容的提问来源于stack exchange,提问作者ally

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:05:48