C++const和operator关键字

const 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Test{
public:
int value = 1;
void getvalue() const{
// this->value = 2;//wrong,常成员函数不可修改成员变量
}
void setvalue(){
this->value = 2;//true
}
};
void test(){
const Test name;
//name.value = 10;//wrong,不可修改
// Cannot assign to variable 'name' with const-qualified type 'const Test'
// name.setvalue();//wrong常量类不可执行非常量函数
//'this' argument to member function 'setvalue' has type 'const Test', but function is not marked const
name.getvalue();//ture
}

在类中定义下面类型算重载不算重复定义

1
2
3
4
5
6
7
8
class Test{
void test(){

}
void test()const{

}
};

operator关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class OverLoad{
public:
int value = 0;
int num = 0;
OverLoad(){ }
OverLoad(int value,int num = 0){
this->value = value;
this->num = num;
}
OverLoad operator +(const OverLoad&a){
this->value += a.value;
this->num += a.num;
return OverLoad(this->value,this->num);
}//重载为成员函数时操作数比操作符数量少1.
void get_value()const{
cout<<"the value is "<<this->value<<endl;
}

};
//OverLoad operator + (const OverLoad &a, const OverLoad &b){
// return OverLoad(a.value+b.value, a.num+b.num);
//}//重载为普通函数时操作数等于操作符数量
void OverLoadTest(){
OverLoad a(10,5),b(20,5);
OverLoad c;
c = a + b;
c.get_value();
}