c++类和对象(三、指针、string相关内容,静态成员)

指针相关

自引用指针this

就是一个访问而已。

class compute
{
public:
	compute(int a, int b);
	compute(const compute& p);//拷贝构造函数,不自定义也可以,编译器会自动生成
	~compute();
	int subst();
private:
	int c_a, c_b;
};

compute::compute(int a, int b)
{
	this->c_a = a;
	this->c_b = b;
}

对象数组

类名 数组名[下标表达式]
用只有一个参数的构造函数给对象数组赋值
Exam ob[4] = {89, 97, 79, 88};
用不带参数和带一个参数的构造函数给对象数组赋值
Exam ob[4] = {89, 90};
用带有多个参数的构造函数给对象数组赋值
Score rec[3] = {Score(33, 99), Score(87, 78), Score(99, 100)};

对象指针

格式:类名 *对象指针名 = &对象

int main()
{
	compute obj1(2,3);
	compute* p = &obj1;
	p->subst();

}

strings类

使用string类必须包含:#include <string>

常用的string类字符有:

=、+、+=、==、!=、<、<=、>、>=、[](访问下标对应字符)、>>(输入)、<<(输出)

部分示例:

#include <iostream>
#include <string>
using namespace std;
int main()
{
	std::string str1 = "Abc";
	std::string str2 = "def";
	
	std::string str3 = str1;// '=' 的应用
	// '+'
	string str4 = str1 + str2;
	str2 += str2; // '+='
	
	cout << "str2 == str3?" << (str2 == str3) << endl;
	cout << "str2 == str3?" << (str2 != str3) << endl;
}

向函数传递对象

1、使用对象作为函数参数

格式:

类型 函数名 (类名 对象形参){}

2、使用对象指针作为函数参数

格式: 类型 函数名 (类名 对象指针形参){}

3、使用对象引用作为函数参数**(主流)

格式:  类型 函数名 (类名 &对象引用形参){}

#include <iostream>
#include <string>
using namespace std;

class Point
{
public:
	int x, y;
	Point(int x1, int y1) :x(x1), y(y1){}//构造函数
	int get_squrt()
	{
		return x * x + y * y;
	}

};
void changepoint1(Point point)//对象作为函数参数
{
	point.x += 1;
	point.y += 1;
}
void changepoint2(Point* p)//对象指针作为函数参数
{
	p->x += 1;
	p->y += 1;
}
void changepoint3(Point& point)//对象引用作为函数参数
{
	point.x += 1;
	point.y += 1;
}

int main()
{
	Point point1(0, 0);
	Point point2(3, 3);
	Point point3(6, 6);
	changepoint1(point1);
	cout << "对象作为函数参数" << point1.get_squrt() << endl;
	Point* p = &point2;
	changepoint2(p);
	cout << "对象指针作为函数参数" << p->get_squrt() << endl;
	changepoint3(point3);
	cout << "对象引用作为函数参数" << point3.get_squrt() << endl;

}

静态成员

定义:在类中,如果某一成员前面声明了static,则该成员为静态成员(数据、函数都可以静态声明)。

作用:无论创建了多少个对象,都只有一个静态成员的拷贝,从而实现多个对象的数据共享。

格式:

static 数据类型 成员名;

静态成员函数格式:

类名::静态成员函数名(实参表);
对象.静态成员函数名(实参表);
对象指针->静态成员函数名(实参表);

友元

 作用:可以直接通过友元访问类的私有成员,从而达到节省空间和计算量的目的。

声明时在成员函数前加上声明friend即可,格式如下:

friend 函数类型 函数名(函数参数)

#include <iostream>
#include <string>
using namespace std;

class cls1
{
public:
	cls1();
	friend int add(int x, int y);
};

class cls2
{
public:
	cls2();
	friend int add(int x, int y);
};

cls1::cls1(){}
cls2::cls2(){}

int add(int x, int y)
{
	return x + y;
}

 此外,还可以将一个类声明为另一个类的友元类。

class Y{
    ···
};
class X{
    friend Y;    //声明类Y为类X的友元类
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值