C++使用struct,class来定义一个类:
struct的默认成员权限是public
class的默认成员权限是private
class Student{
private:
string name;
double score;
public:
double GetScore(){
return score;
}
}
让自定义的类像内置类型一样
如果现在有一个自定义的复数类型,那么它的操作应该是可以像使用int一样自然的使用它,同时它对我们是一个黑盒,一种抽象
Complex.h
#pragma once
class Complex
{
public:
Complex();//构造函数
Complex(couble r,double i);//构造函数
virtual~();//析构函数,通常都要加上virtual(因为承继体系)
double getReal()const{return _real;}
void setReal(double d){_real=d;}
double getImage()const{return _image;}
void setImage(double i){_image=i;}
//运算符重载
Complex operator+(const Complex& x);
Complex& operator=(const Complex& x);
//前置和后置++,--
Complex& operator++ ();//前置++
Complex operator++();//后置++
//标准输入输 出IO重载
friend ostream& operator<<(ostream& os,const Complex &x);
friend istream& operator>>(istream& is,Complex &x);
private:
double _real;//复数的虚部
double _image;//复数的虚部
}
Complex.cpp
#include "Complex.h"
Complex::Complex(){
_real=0;
_image=0;
cout << "Complex::Complex()"<< endl;
}
Complex::Complex(couble r,double i){
_real=r;
_image=i;
cout << "Complex::Complex(couble r,double i)"<< endl;
}
Complex& Complex::operator=(const Complex& x){
if(this!=&x){
_real=x._real;
_image=x._image;
}
return *this;
}
Complex::Complex(){
cout << "Complex::Complex()"<< endl;
}
Complex Complex::operator+(const Complex& x){
Complex tmp;
tmp._real=_real+x._real;
tmp._image=_image+x._image;
return tmp;//temp是一个栈上变量,不能直接传递。此处会产生拷贝构造对象。
//可优化为 return Complex(... , ...);不产生临时变量
}
Complex& Complex: operator++ ()
{
_real++;
_image++;
return *this;
}
Complex Complex:operator++()
{
Complex tmp(*this);
_real++;
_image++;
return tmp;
}
ostream& operator<<(ostream& os,const Complex &x)
{
os << "real value is " << x._real <<",image value is "<< x._image ;
return os;
}
istream& operator>>(istream& is,Complex &x)
{
is >> x._real >> x._image; //输入时以空格或回车分隔两个数据。
return is;
}
#include "Complex.h"
#include <iostream>
using namespace std;
int main{
Complex a(1.0,2.0);
cout << a.getReal()<<endl;//1.0
cout << a.getImage()<<endl;///2.0
a.setImage(2.0);
a.setReal(3.0);
cout << a.getReal()<<endl;//3.0
cout << a.getImage()<<endl;///2.0
Complex b(1.0,2.0);
Complex c;
c=a+b;//运算符重载函数生效
//Complex c=a+b;//此处避免调用一次默认构造,而直接使用有参构造。
//Complex d(c);//调用拷贝构造
return 0;
}