#include

using namespace std; //using std::cout; class Person; // 声明

class Dog { public: int getValue() { return m_value; } void setValue(int value); // 成员函数的声明 protected: int m_value; private: int m_pri; friend int main(); // 友元函数 friend class Person; // 友元类 };

class Person { public: void showDog(const Dog &dg) { cout << dg.m_value << endl; } };

void Dog::setValue(int value) { m_value = value; }

int main() { Dog dog; dog.setValue(10); cout << dog.getValue() << endl;

Person person;
person.showDog(dog);

return 0;

}

解释每行代码:

  1. #include <iostream>:包含输入输出流库。
  2. using namespace std;:使用std命名空间。
  3. class Person;:声明了一个名为Person的类。
  4. class Dog:定义了一个名为Dog的类。
  5. public:protected:private::定义了成员的访问权限,public表示公共成员,protected表示保护成员,private表示私有成员。
  6. int getValue():定义了一个返回值为int类型的成员函数getValue(),用于获取m_value的值。
  7. void setValue(int value);:声明了一个返回值为void的成员函数setValue(),用于设置m_value的值。
  8. int m_value;:定义了一个名为m_value的整型成员变量。
  9. int m_pri;:定义了一个名为m_pri的整型私有成员变量。
  10. friend int main();:声明了一个名为main()的友元函数。
  11. friend class Person;:声明了一个名为Person的友元类。
  12. class Person:定义了一个名为Person的类。
  13. void showDog(const Dog &dg):定义了一个返回值为void的成员函数showDog(),用于输出Dog类的m_value的值。
  14. cout << dg.m_value << endl;:输出Dog类的m_value的值。
  15. void Dog::setValue(int value):定义了Dog类成员函数setValue()的实现。
  16. m_value = value;:将参数value的值赋给成员变量m_value。
  17. int main():定义了主函数。
  18. Dog dog;:创建了一个Dog类的对象dog。
  19. dog.setValue(10);:调用Dog类的成员函数setValue(),将参数10传入。
  20. cout << dog.getValue() << endl;:输出Dog类的成员函数getValue()返回的值。
  21. Person person;:创建了一个Person类的对象person。
  22. person.showDog(dog);:调用Person类的成员函数showDog(),将dog作为参数传入。
  23. return 0;:返回0,表示程序正常结束。
C++ 类和友元:Dog 和 Person 示例详解

原文地址: https://www.cveoy.top/t/topic/qlEA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录