c++ 友元函数
测试友元函数。
头文件TestCls1.h:
#pragma once
#include <cstdint>using UINT32 = uint32_t; // 别名// 测试友元函数
class TestCls1
{private:int x, y;public:void setX(UINT32 x);void setY(UINT32 y);friend void printTestCls1(const TestCls1& v); // 友元函数声明
};// 需单独声明函数(可放在头文件中)
void printTestCls1(const TestCls1& v); // 实际函数声明,不能缺少,否则外部文件不知道这个函数
源文件TestCls1.cpp:
#include "TestCls1.h"
#include <iostream>void printTestCls1(const TestCls1& testCls) { // 友元函数的定义std::cout << testCls.x << ", " << testCls.y; // 可访问类的私有成员
}void TestCls1::setX(UINT32 x)
{this->x = x;
}void TestCls1::setY(UINT32 y)
{this->y = y;
}
测试代码:
#include "TestCls1.h"void testFriendFunc() {TestCls1 testCls1;testCls1.setX(9527);testCls1.setY(1314520);printTestCls1(testCls1);
}
打印:
注意:友元函数不是类的成员函数,所以没有this指针。友元函数可以访问类的所有成员,包含私有和受保护成员。