重学C++(1)——几个常常忽视的简单的类的问题

重新开始学习C++,发现了几个很容易忽视的问题:

1、构造函数的值拷贝,对于指针而言是直接拷贝地址

2、const后的类,只能使用const的成员函数

3、对于const成员函数,使用指针和引用可以破坏const性,从而修改类中成员的值

下面程序来说明这几个问题:

text.cpp

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Text
{
 friend ostream& operator<<( ostream &os, const Text &text );
public:
 Text( string, char* cstr );
 string val() const { cout << "val() const" << endl; return _val; }
 string val() { cout << "val()" << endl; return _val; }
 void bad( const string &parm ) const;
 void print() { cout << "print...." << endl; }
 void print() const { cout << "print const...." << endl; }
private:
 string _val;
 char *_cstr_val;
};

Text::Text( string val = "defalt", char *cstr = "default _cstr_val" ) :
 _val( val ),
 _cstr_val( cstr )
{
 cout << "Creating a Text..." << endl;
 printf( "cstr :%x, _cstr_val: %x/n", cstr, _cstr_val );
}

void Text::bad( const string &parm ) const
{
 //_val = parm;
 
 for( int ix = 0; ix < parm.size(); ix++ )
 {
  _cstr_val[ix] = parm[ix];  //if u come here it will coredump haha
 }
}

ostream& operator<<( ostream &os, const Text &text )
{
 os << "Text value: " << text.val() << endl;
 os << "Text cstring value: " << text._cstr_val << endl;
 return os;
}

int main()
{
 Text t;
 cout << "t: " << t << endl;
 cout << "t.val() :" << t.val() << endl;
 
 //t.bad("test");     //will coredump if u want to do this
 //cout << t << endl;
 
 const Text t1 = t;
 cout << "t1: " << t1 << endl;
 cout << "t1.val() :" << t1.val() << endl;
 
 t.print();  //print
 t1.print();  //print const
 
 return 0;
}

cout << t;可以看到,_cstr_val和函数参数cstr的地址是同一个,所以值拷贝对于指针而言,就是地址的拷贝,bad函数虽然表明是一个const的成员函数,但是对于_cstr_val指针的值却是可以改变,这在逻辑上是说的过去的_cstr_val的指针地址依然没有变,变的是该地址上存放的内容罢了,不过本程序中,如果执行bad()这个函数,程序会coredump,理由?你试试下面这条语句:char *test = "test"; test[0] = '/0';两者coredump的原因一样。后面的print函数不用说了,就是const对象使用const成员函数,如果没有void print() const,那么t1.print()是没法编译通过的。

有时真的觉得C++的类型检查是个很烦人的东西,不过,相比起来,泛型算法就是噩梦了。侯捷说“C++是难学易用的语言”,看来是真的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值