类的成员函数
#include<iostream> // c++标准头文件
#include<stdio.h> // C语言标准头文件,包含".h"
#include<ctime>
#include<opencv2/opencv.hpp>
// 命名空间,避免命名污染
using namespace std;
using namespace cv;
class Girlfriend
{
int d = 4; // 默认私有属性
// 类内部、类成员函数、继承类均可访问
public:// 共有属性
int a = 1;
int age;
// 构造函数
Girlfriend() {
cout << "默认构造函数" << endl;
}
Girlfriend(int age){
cout << "包含参数的构造函数," << endl;
}
~Girlfriend() {
cout << "析构函数" << endl;
}
void test(){}
// 可由类的成员函数和友元(类或函数)使用
protected://保护属性
int b = 1;
// 仅类内部成员可以访问
private: // 私有属性
int c = 1;
// 友元函数
friend void ChangePrivate(Point & );
};
void ChangePrivate(Point & i) {i.m_i++;}
int main()
{
Girlfriend mm;
Girlfriend MM1;
Girlfriend* p = new Girlfriend(12);
// 访问成员变量
p->test();
return 0;
}
友元函数
友元函数:一个不为类成员的函数,但它可以访问类的私有和受保护的成员
友元函数不被视为类成员;它们是获得了特殊访问权限的普通外部函数。 友元不在类的范围内,除非它们是另一个类的成员,否则不会使用成员选择运算符(. 和 ->)调用它们。 friend 函数由授予访问权限的类声明。 可将 friend 声明放置在类声明中的任何位置。 它不受访问控制关键字的影响。
虚拟函数
对于某些函数,当基类希望派生类重新定义合适自己的版本时,基类就把这些函数声明为虚函数
#include <iostream>
#include <string>
using namespace std;
// 基类
class dog
{
public:
dog()
{
_legs = 4;
_bark = true;
}
void setDogSize(string dogSize)
{
_dogSize = dogSize;
}
// 虚拟函数,在子类中进行重写
virtual void setEars(string type) // virtual function
{
_earType = type;
}
private:
string _dogSize, _earType;
int _legs;
bool _bark;
};
#子类
class breed : public dog
{
public:
breed( string color, string size)
{
_color = color;
setDogSize(size);
}
string getColor()
{
return _color;
}
// virtual function redefined:重写虚拟函数
void setEars(string length, string type)
{
_earLength = length;
_earType = type;
}
protected:
string _color, _earLength, _earType;
};
int main()
{
dog mongrel;
breed labrador("yellow", "large");
mongrel.setEars("pointy");
labrador.setEars("long", "floppy");
cout << "Cody is a " << labrador.getColor() << " labrador" << endl;
}
本文详细介绍了C++中的类的成员函数,包括公有、保护和私有属性,构造函数和析构函数,以及友元函数的概念。此外,还探讨了如何使用虚拟函数实现基类和派生类的灵活性。
923

被折叠的 条评论
为什么被折叠?



