复习笔记(六)——C++运算符重载(难点)

运算符重载

运算符重载的概念

运算符重载类似于函数重载。

运算符重载允许把标准运算符(如+-*<等)应用于定制数据类型的对象。

什么情况下需要考虑运算符重载?
需要用运算符操作自定义类的对象时,如对象之间直观自然,可以提高比较大小等,通过重载支持类的运算。

运算符重载:①体现了程序的可读性;②体现了C++的可扩充性

运算符重载的定义

作为类的成员函数或友元函数、作为一般函数(很少用)。

1、成员函数原型的格式:
函数类型 operator 运算符(参数表);
成员函数定义的格式:

函数类型 类名::operator 运算符(参数表)
{
	函数体;
}

以成员函数的方式重载运算符
-单目运算符:不带参数,该类对象为唯一操作数
-双目运算符:带一个参数,该类对象为左操作数、参数为右操作数


2、友元函数原型的格式:
friend 函数类型 operator 运算符(参数表);
友元函数定义的格式:

函数类型 operator 运算符(参数表)
{
	函数体;
}

以友元函数的方式重载运算符
-单目运算符:带一个参数,该参数为唯一操作数,是自定义类的对象 ++(a)
-双目运算符:带两个参数,第一个参数为左操作数、第二个参数为右操作数,至少有一个参数为自定义类的对象
+(a, b)

实例

#include <iostream>
using namespace std;

class Complex
{
public:
    Complex(double = 0.0, double = 0.0);
    Complex operator+(const Complex&) const;
    Complex Add(const Complex&) const;
    Complex operator-(const Complex&) const;
    Complex& operator=(const Complex&);
    void print() const;
private:
    double real;       // real part
    double imaginary;  // imaginary part
};
Complex::Complex(double r, double i)
{
    real = r;
    imaginary = i;
}
Complex Complex::operator+(const Complex &operand2) const
{
  Complex sum;
  sum.real = this->real + operand2.real;
  sum.imaginary= this->imaginary + operand2.imaginary;
  return sum;
}
Complex Complex::Add(const Complex &operand2) const
{
    //功能的实现同上
}
Complex Complex::operator-(const Complex &operand2) const
{
    Complex diff;
    diff.real = real - operand2.real;
    diff.imaginary=imaginary - operand2.imaginary;
    return diff;
}
Complex& Complex::operator=(const Complex &right)
{
    real = right.real;
    imaginary = right.imaginary;
    return *this;   // enables concatenation
}
void Complex::print() const
{
    cout<<'('<<real<< "," << imaginary << ')';
}
int main()
{
    Complex x, y(4.3, 8.2), z(3.3, 1.1);
    cout << "x: ";	x.print();
    cout << "\ny: ";	y.print();
    cout << "\nz: ";	z.print();
    x = y + z;	//比表达式x=y.Add(z);更简练,更直观
    cout << "\n\nx = y + z:\n";	x.print();
    cout << " = ";		y.print();
    cout << " + ";		z.print();

    return 0;
}

执行结果:

x: (0,0)
y: (4.3,8.2)
z: (3.3,1.1)

x = y + z:
(7.6,9.3) = (4.3,8.2) + (3.3,1.1)

运算符重载的规则

①运算符重载不允许发明新的运算符。

②不能改变运算符操作对象的个数。

③运算符被重载后,其优先级和结合性不会改变。

④不能重载的运算符:
在这里插入图片描述

一元运算符重载

操作数是自定义类的对象或对象的引用。

作为成员函数重载没有参数。

作为友元函数重载参数为自定义类的对象或对象的引用(概念介绍)。

实例

(成员函数的方式重载!)

#include <iostream>**自增、自减运算符重载**
#include <string.h>
using namespace std;

class CString
{
public:
    CString(const char *s="");
    CString(const CString& s);
    ~CString();
    CString& operator = (const CString& s);
    CString& operator = (const char *s);
    bool operator !();
    char *m_str;
private:
    int m_size;
};
CString::CString(const CString& s)
{
    m_size=strlen(s.m_str);
    m_str=new char[m_size+1];
    strcpy(m_str,s.m_str);
}
CString::CString(const char *s/* ="" */)
{
    m_size=strlen(s);
    m_str=new char[m_size+1];
    strcpy(m_str,s);
}
bool CString::operator !()
{
    if (strlen(m_str)==0)
    {
        return true;
    }
    else
        return false;
}
CString::~CString()
{
    delete []m_str;
}
int main()
{
    CString s1, s2("some string");
    if (!s1)//括号中等价于s1.operator!()=>显示调用
        cout<<"s1 is NULL!"<<endl;
    else   cout<<"s1 is not NULL!"<<endl;
    if (!s2)
        cout<<"s2 is NULL!"<<endl;
    else
        cout<<"s2 is not NULL!"<<endl;
    return 0;
}

执行结果:

s1 is NULL!
s2 is not NULL!

自增、自减运算符重载

在C++中,单目运算符有++和- -,它们是变量自动增1和自动减1的运算符。在类中可以对这两个单目运算符进行重载。

前置自增和前置自减的重载:
1、成员函数的方式重载,原型为:
函数类型 & operator++();
函数类型 & operator--();
2、友元函数的方式重载,原型为:
函数类型 & operator++(类类型 &);
函数类型 & operator--(类类型 &);

后置自增和后置自减的重载:
1、成员函数的方式重载,原型为:
函数类型 operator++(int);
函数类型 operator--(int);
2、友元函数的方式重载,原型为:
函数类型 operator++(类类型 &,int);
函数类型 operator--(类类型 &,int);

使用前缀运算符的语法格式:++<对象>;
使用后缀运算符的语法格式:<对象>++;

实例

#include <iostream>
using namespace std;

class  CInt
{
public:
    CInt(int a=0);
    void Print();
    CInt &operator ++();
    CInt  operator ++(int);
private:
    int i;
};
CInt::CInt (int  a)
{
    i = a;
}
void CInt::Print()
{
    cout << "i=" << i << endl;
}
CInt &CInt::operator ++()
{
    ++i;
    return *this;
}
CInt  CInt::operator ++(int)
{
    CInt sum;
    sum=*this;
     ++i;
    return sum;
}
int main(void)
{
    CInt  a(5), b(5), c, d;
    c = a++;
    d = ++b;
    cout << "a: ";a.Print();
    cout << "b: ";b.Print();
    cout << "c: ";c.Print();
    cout << "d: ";d.Print();

    return 0;
}

执行结果:

a: i=6
b: i=6
c: i=5
d: i=6

二元运算符重载

1、成员函数的方式重载二元运算符
函数原型:
函数类型 operator 二元运算符(类型 参数);
带有一个参数
左操作数必须为该类的对象或对象的引用

2、二元运算符重载为带有两个参数的非成员函数
函数原型:
函数类型 operator 二元运算符(类型 参数1,类型 参数2);
参数之一必须是类的对象或对象的引用

赋值运算符的重载

1、赋值运算符可直接用在自定义类的对象赋值。

2、如果没有提供重载的赋值运算符函数来复制类的对象。编译器就会提供默认版本的operator=()

3、赋值运算符的默认版本会简单地进行逐个成员的复制过程,类似于默认的拷贝构造函数。

4、运算符“=”重载时,要检查两个操作数是否为同一个对象。

5、如果对象中包含动态分配的空间,这种赋值方式就不合适了,如:

CString s1("abc"), s2("def");  //具体类见一元运算符重载实例
s1 = s2;

赋值的结果是:对象s1和s2的指针str都指向了同一块数据空间。

6、对象中包含动态分配的空间,赋值运算符需要自己重载,函数实现的算法与拷贝构造函数类似。

实例

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

class CString
{
public:
    CString(const char *s="");
    CString(const CString& s);
    CString & operator = (const CString & s);
    CString & operator = (const char *s);
    char *m_str;
private:
    int m_size;
};
CString::CString(const CString& s)
{
    m_size=strlen(s.m_str);
    m_str=new char[m_size+1];
    strcpy(m_str,s.m_str);
}
CString::CString(const char *s/* ="" */)
{
    m_size=strlen(s);
    m_str=new char[m_size+1];
    strcpy(m_str,s);
}
CString& CString::operator =(const CString& str)
{
    if (this!=&str)
    {
        delete[] m_str;
        m_size=strlen(str.m_str);
        m_str=new char[m_size+1];
        strcpy(m_str,str.m_str);
    }
    return *this;
}
CString& CString::operator =(const char *str)
{
    delete[] m_str;
    m_size=strlen(str);
    m_str=new char[m_size+1];
    strcpy(m_str,str);
    return *this;//为什么需要返回值?
}
int main()
{
    CString s1("abc"),s2(s1),s3;
    s3=s2;
    cout<<"s1:"<<s1.m_str<<endl;	//m_str应该声明成私有,如何输出
    cout<<"s2:"<<s2.m_str<<endl;	//cout<<s2;
    cout<<"s3:"<<s3.m_str<<endl;
    s3="tom";
    cout<<"s3:"<<s3.m_str<<endl;
    return 0;
}

执行结果:

s1:abc
s2:abc
s3:abc
s3:tom

‘+’运算符重载的使用

实例

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

class CString
{
public:
    CString(const char *s="");
    CString(const CString& s);
    CString  operator + (const CString &s);
    CString  operator + (const char *s);
    CString & operator = (const CString & s);
    CString & operator = (const char *s);
    char *m_str;
private:
    int m_size;
};
CString::CString(const CString& s)
{
    m_size=strlen(s.m_str);
    m_str=new char[m_size+1];
    strcpy(m_str,s.m_str);
}
CString::CString(const char *s/* ="" */)
{
    m_size=strlen(s);
    m_str=new char[m_size+1];
    strcpy(m_str,s);
}
CString CString::operator+(const CString &s)
{
    CString tempStr;
    char *p=new char[strlen(this->m_str)+strlen(s.m_str)+1];
    if(p==NULL){exit(1);}
    strcpy(p,this->m_str);
    strcat(p,s.m_str);
    tempStr.m_str=p;
    return tempStr;
}
CString CString::operator+(const char *s)
{
    CString tempStr;
    char *p=new char[strlen(this->m_str)+strlen(s)+1];
    strcpy(p,this->m_str);
    strcat(p,s);
    tempStr.m_str=p;
    return tempStr;
}
CString& CString::operator =(const CString& str)
{
    if (this!=&str)
    {
        delete[] m_str;
        m_size=strlen(str.m_str);
        m_str=new char[m_size+1];
        strcpy(m_str,str.m_str);
    }
    return *this;
}
CString& CString::operator =(const char *str)
{
    delete[] m_str;
    m_size=strlen(str);
    m_str=new char[m_size+1];
    strcpy(m_str,str);
    return *this;
}
int main()
{
    CString s1="hello",s2("world"),s3;
    s3=s1+s2;
    cout<<"s3 = s1+s2 -- "<<s3.m_str<<endl;
    s3=s3+"abc"; 
    //s3="abc"+s1;	//会出现什么问题?? =>会报错:no match for 'operator+' in '"abc" + s1'
    cout<<"s3:"<<s3.m_str<<endl;

    return 0;
}

执行结果:

s3 = s1+s2 -- helloworld
s3:helloworldabc

重载运算符‘[ ]’

实例

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

class CString
{
public:
    CString(const char *s="");
    CString(const CString& s);
    char operator [](int index);
    int GetSize();
    char *m_str;
private:
    int m_size;
};
CString::CString(const CString& s)
{
    m_size=strlen(s.m_str);
    m_str=new char[m_size+1];
    strcpy(m_str,s.m_str);
}
CString::CString(const char *s/* ="" */)
{
    m_size=strlen(s);
    m_str=new char[m_size+1];
    strcpy(m_str,s);
}
inline int CString::GetSize()
{
    return m_size;
}
char CString:: operator [](int index)
{
    if(index<0 || index>=m_size)
    {//下标越界
    }
    return m_str[index];
}
int main()
{
    CString entry("extravagant");
    for(int i = 0;i<entry.GetSize();++i)
    {
        cout<<"entry = "<<entry[i]<<endl;
    }
    return 0;
}

执行结果:

entry = e
entry = x
entry = t
entry = r
entry = a
entry = v
entry = a
entry = g
entry = a
entry = n
entry = t
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 好的,下面是SparkSQL代码笔记03——连接Hive的中文回复: 在SparkSQL中,我们可以通过以下步骤连接Hive: 1. 首先,需要在SparkSession中启用Hive支持,可以使用以下代码: ``` from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("SparkSQL Hive Example") \ .config("spark.sql.warehouse.dir", "/user/hive/warehouse") \ .enableHiveSupport() \ .getOrCreate() ``` 其中,`enableHiveSupport()`方法启用了Hive支持,`config("spark.sql.warehouse.dir", "/user/hive/warehouse")`指定了Hive元数据存储的目录。 2. 接下来,我们可以使用`spark.sql()`方法执行Hive SQL语句,例如: ``` spark.sql("show databases").show() ``` 这将显示所有的Hive数据库。 3. 如果需要在SparkSQL中访问Hive表,可以使用以下代码: ``` df = spark.sql("select * from my_hive_table") ``` 其中,`my_hive_table`是Hive中的表名。 4. 如果需要在SparkSQL中创建Hive表,可以使用以下代码: ``` spark.sql("create table my_hive_table (id int, name string)") ``` 这将在Hive中创建一个名为`my_hive_table`的表,包含两个列:`id`和`name`。 以上就是连接Hive的基本步骤。需要注意的是,连接Hive需要在Spark集群中安装Hive,并且需要将Hive的JAR包添加到Spark的CLASSPATH中。 ### 回答2: SparkSQL是Apache Spark的一个组件,它提供了用于分布式数据处理的高级SQL查询引擎。SparkSQL支持连接多种数据源,其中之一就是Hive。 如何连接Hive? 在开始连接Hive之前,我们需要确保Hadoop和Hive的配置已经被正确的设置好了,以便Spark能够访问Hive元数据和数据。 首先,我们需要在Spark环境中添加Hive支持。运行下面的代码: `from pyspark.sql import SparkSession spark = SparkSession.builder \ .appName("hive_support") \ .enableHiveSupport() \ .getOrCreate()` 其中,`.enableHiveSupport()`将启用hive支持。 接下来,我们可以使用SparkSession连接Hive。运行下面的代码: `hive_df = spark.sql("SELECT * FROM default.student")` 其中,“default”是Hive的默认数据库,“student”是Hive数据库中的表名。 如果你要访问非默认的Hive数据库,可以使用下面的代码: `hive_df = spark.sql("SELECT * FROM dbname.student")` 其中,“dbname”是非默认的Hive数据库名。 我们还可以使用HiveContext来连接Hive。运行下面的代码: `from pyspark.sql import HiveContext hive_context = HiveContext(sc)` 其中,“sc”是SparkContext对象。 我们可以像这样从Hive中检索数据: `hive_df = hive_ctx.sql("SELECT * FROM default.student")` 现在你已经成功地连接Hive并从中检索了数据,你可以使用SparkSQL的强大功能对数据进行分析。而在连接Hive之外,在SparkSQL中还可以连接其他数据源,包括MySQL、PostgreSQL、Oracle等。 ### 回答3: Spark SQL是一个强大的分布式计算引擎,它可以支持处理多种数据源,并可通过Spark SQL shell、Spark应用程序或JDBC/ODBC接口等方式进行操作。其中,连接Hive是Spark SQL最常用的数据源之一。下面,将介绍如何通过Spark SQL连接Hive。 1、在Spark配置中设置Hive Support 要连接Hive,首先需要在Spark配置中开启Hive Support。在启动Spark Shell时,可以添加如下参数: ``` ./bin/spark-shell --master local \ --conf spark.sql.warehouse.dir="/user/hive/warehouse" \ --conf spark.sql.catalogImplementation=hive \ --conf spark.sql.hive.metastore.version=0.13 \ --conf spark.sql.hive.metastore.jars=maven ``` 这里以本地模式为例,设置Spark SQL的元数据存储在本地文件系统中,设置Hive为catalog实现,以及为Hive Metastore设置版本和JAR文件路径。根据实际情况,还可以指定其他参数,如Hive Metastore地址、数据库名称、用户名和密码等。 2、创建SparkSession对象 在连接Hive之前,需要先创建SparkSession对象。可以通过调用SparkSession.builder()静态方法来构建SparkSession对象,如下所示: ``` val spark = SparkSession.builder() .appName("SparkSQLTest") .config("spark.sql.warehouse.dir", "/user/hive/warehouse") .enableHiveSupport() .getOrCreate() ``` 这里通过builder()方法指定应用程序名称、元数据存储路径以及启用Hive Support,最后调用getOrCreate()方法创建SparkSession对象。 3、通过Spark SQL操作Hive表 通过Spark SQL连接Hive后,就可以通过Spark SQL语句来操作Hive表了。例如,我们可以使用select语句查询Hive表中的数据: ``` val df = spark.sql("SELECT * FROM tablename") df.show() ``` 其中,select语句指定要查询的列和表名,然后通过show()方法来显示查询结果。 除了查询数据之外,Spark SQL还可以通过insertInto语句将数据插入到Hive表中: ``` val data = Seq(("Alice", 25), ("Bob", 30)) val rdd = spark.sparkContext.parallelize(data) val df = rdd.toDF("name", "age") df.write.mode(SaveMode.Append).insertInto("tablename") ``` 这里先创建一个包含数据的RDD对象,然后将其转换为DataFrame对象,并指定列名。接着,通过insertInto()方法将DataFrame对象中的数据插入到Hive表中。 总之,通过Spark SQL连接Hive可以方便地查询、插入、更新和删除Hive表中的数据,从而实现更加灵活和高效的数据处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

别呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值