C++ 类和友元:Dog 和 Person 示例详解
#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;
}
解释每行代码:
#include <iostream>:包含输入输出流库。using namespace std;:使用std命名空间。class Person;:声明了一个名为Person的类。class Dog:定义了一个名为Dog的类。public:和protected:和private::定义了成员的访问权限,public表示公共成员,protected表示保护成员,private表示私有成员。int getValue():定义了一个返回值为int类型的成员函数getValue(),用于获取m_value的值。void setValue(int value);:声明了一个返回值为void的成员函数setValue(),用于设置m_value的值。int m_value;:定义了一个名为m_value的整型成员变量。int m_pri;:定义了一个名为m_pri的整型私有成员变量。friend int main();:声明了一个名为main()的友元函数。friend class Person;:声明了一个名为Person的友元类。class Person:定义了一个名为Person的类。void showDog(const Dog &dg):定义了一个返回值为void的成员函数showDog(),用于输出Dog类的m_value的值。cout << dg.m_value << endl;:输出Dog类的m_value的值。void Dog::setValue(int value):定义了Dog类成员函数setValue()的实现。m_value = value;:将参数value的值赋给成员变量m_value。int main():定义了主函数。Dog dog;:创建了一个Dog类的对象dog。dog.setValue(10);:调用Dog类的成员函数setValue(),将参数10传入。cout << dog.getValue() << endl;:输出Dog类的成员函数getValue()返回的值。Person person;:创建了一个Person类的对象person。person.showDog(dog);:调用Person类的成员函数showDog(),将dog作为参数传入。return 0;:返回0,表示程序正常结束。
原文地址: https://www.cveoy.top/t/topic/qlEA 著作权归作者所有。请勿转载和采集!