Skip to content

Commit c007755

Browse files
authored
Update README.md
1 parent c1635d0 commit c007755

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

basic_content/const/README.md

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,8 @@ public:
293293
Apple(int i);
294294
const int apple_number;
295295
void take(int num) const;
296-
int add(int num);
297-
int add(int num) const;
296+
int add();
297+
int add(int num) const;
298298
int getCount() const;
299299

300300
};
@@ -307,9 +307,9 @@ Apple::Apple(int i):apple_number(i)
307307
{
308308

309309
}
310-
int Apple::add(int num){
311-
take(num);
312-
return num;
310+
int Apple::add(){
311+
take(1);
312+
return 0;
313313
}
314314
int Apple::add(int num) const{
315315
take(num);
@@ -322,33 +322,27 @@ void Apple::take(int num) const
322322
int Apple::getCount() const
323323
{
324324
take(1);
325-
// add(); //error
325+
add(); // error
326326
return apple_number;
327327
}
328328
int main(){
329329
Apple a(2);
330330
cout<<a.getCount()<<endl;
331331
a.add(10);
332-
const Apple b(3);
333-
b.add(100);
334332
return 0;
335333
}
336334
```
337335
> 编译: g++ -o main main.cpp apple.cpp<br>
338336
339-
结果:
340-
```
341-
take func 1
342-
2
343-
take func 10
344-
take func 100
345-
```
346-
347-
上面getCount()方法中调用了一个add方法,而add方法并非const修饰,所以运行报错。也就是说const对象只能访问const成员函数。
337+
此时报错,上面getCount()方法中调用了一个add方法,而add方法并非const修饰,所以运行报错。也就是说const成员函数只能访问const成员函数。
348338
349-
而add方法又调用了const修饰的take方法,证明了非const对象可以访问任意的成员函数,包括const成员函数。
339+
当调用改为:
350340
351-
除此之外,我们也看到add的一个重载函数,也输出了两个结果,说明const对象默认调用const成员函数。
341+
```
342+
const Apple b(3);
343+
b.add(); // error
344+
```
345+
此时,可以证明的是const对象只能访问const成员函数。
352346
353347
我们除了上述的初始化const常量用初始化列表方式外,也可以通过下面方法:
354348

0 commit comments

Comments
 (0)