题目:友元成员
#include <iostream>
using namespace std;
class CTest{
public:
CTest() {
x=20;
}
void use_friend();
private:
int x;
friend void friend_f(CTest &fri); // 该友元函数目的是修改私有数据成员x的值,添加&实现地址传参
};
void friend_f(CTest &fri)
{
fri.x=55;
}
void CTest::use_friend()
{
CTest fri;
// this->friend_f(fri); // friend_f()函数不是CTest类的成员函数,this指针无法指向它
::friend_f(fri);
}
int main()
{
CTest fri,fri1;
// fri.friend_f(fri); // friend_f()函数不是CTest类的成员函数,CTest类的对象无法访问它
friend_f(fri1);
return 0;
}
题目:new和delete
#include <iostream>
#include <string>
using namespace std;
class Shape
{
public:
Shape(string name)
{
this->name=name;
cout << "构造";
cout <<this->name<<endl;
}
~Shape()
{
cout << "析构";
cout<<this->name<<endl;
}
private:
string name;
};
int main()
{
Shape a("图形A");
Shape* b = new Shape("图形B"); // 用new建立了一个堆对象
delete b;
return 0;
}
有delete b; :
使用类名定义对象和使用new运算符建立堆对象都会调用构造函数,main程序结束之前调用析构函数释放内存。且构造函数与析构函数调用顺序相反。
注释掉delete b; :
使用new建立对象建在堆区,需要程序员手动释放。如果不手动释放,内存会堆积越来越多,可能出现内存泄漏。当退出程序后操作系统清空内存。
题目:对象数组
#include <iostream>
using namespace std;
class Book {
private :
int number; // 数量
int price; // 价格
public :
Book(int number) {
this