类的构造函数简化
给构造函数默认值,可以应用不同数量参数情况
class Node{
private:
int a;
int b;
int c;
public:
Node(int a = 0,int b = 0,int c = 0){
this->a = a;
this->b = b;
this->c = c;
}
};
//在创建Node的时候使用(返回指针)
new Node(1,2,3);
new Node(1,2);
new Node(1);
//都可以用,会默认参数初始值
类的函数体的类外定义
类的函数体是可以放在此类的外面进行定义的,但要声明命名空间
class Node{
private:
int a;
int b;
int c;
public:
Node(int a = 0,int b = 0,int c = 0){
this->a = a;
this->b = b;
this->c = c;
}
void show();
};
void Node::show(){//如果在类外定义,就需要加一个命名空间NOde::让程序知道这个函数是哪个类的
cout << this->a <<endl;
}
类的private成员调用
类的private成员只能由该类的函数,友元函数访问
如果某类中传入另一个类参数,可以直接调用此参数的private属性,因为参数也属于类的一部分
#include<iostream>
using namespace std;
class Node{
private:
int a;
int b;
int c;
public:
Node(int a = 0,int b = 0,int c = 0){
this->a = a;
this->b = b;
this->c = c;
}
void show();
void add(Node x){
a += x.a;//这里可以直接用x.a调用x的private属性
}
};
int main(){
Node *node = new Node(1,2,3);
cout << node->a <<endl;//错误,不可以直接调用类的private属性
return 0;
}
操作符重载
把函数名换成operator和操作符
如operator+
operator-
operator*
操作符重载本质上还是函数重载,可以把操作符看作一个特殊的函数
注意,不能创造操作符,操作符两边的操作数个数不能变,操作符的优先级不能变,操作符两边的对象类型,根据operator两边决定
Node operator+ (Node z){
....
}
//然后就可以使用a+z,实现了操作符重载
#include<iostream>
using namespace std;
class Node{
private:
int a;
int b;
int c;
public:
Node(int a = 0,int b = 0,int c = 0){
this->a = a;
this->b = b;
this->c = c;
}
void show(){
cout << this->a <<" "<< this->b << " "<< this->c<<endl;
}
Node operator+ ( Node z);
};
Node Node::operator+(Node z){//类函数的外部定义以及操作符重载
Node x(a,b,c);
x.a += z.a;
x.b += z.b;
x.c += z.c;
return x;
}
int main(){
Node node(1,2,3);
Node x = node + node;
x.show();
node.show();
return 0;
}