C++高手请进(100分)

教父

Unregistered / Unconfirmed
GUEST, unregistred user!
在《Essential C++》的P111页中有这样一个例子:
class val_class {
public:
val_class(const BigClass &v):_val(v)()
BigClass &amp
val() const {return _val;} //此句是否有问题?
private:
BigClass _val;
};
书中说这会产生问题(但语法层面正确),返回一个non-const reference 指向_val,实际上
等于将_val开放出去,允许程序在其它地方加以修改。

我现在想问:我怎么在其它地方修改这个_val值?

为此我定义了一个类:
class Ctest
{
private:
string _title;
public:
Ctest(const string&amp
title):_title(title){}
string&amp
title() {return _title;}
};
void main(void)
{
Ctest t("zyp");
string Title;
Title=t.title();
cout << "The old t.title is " << Title <<endl;
Title="lq";
cout << "Title is " << Title << endl;
cout << "The new t.title is " << t.title() << endl;
}
这段代码并不能修改_title的值。
请各位高手指点。
 
Title.erase(Title.begin(),Title.end());
will erase the content of the string.
 
string Title;
Title=t.title();
关键是这两句,t.title()是_title的引用,
但是Title并不是引用,这样写相当于Title = _title;
如果改成这样string&amp
Title = t.title();Title与_tilte就是同一个实体,
就会修改_title.
 
jps_exp兄是对的,以后还请多多指点。
同样也非常感谢JJams_King的热心帮助。 :)
 
Ohh, I mistook "string Title" for "string&amp
Title"

Reference is something of a pointer.
Hope this will help understand it:

string&amp
Title=t.title()
<==> string* pTitle = t.title();
string Title = t.title()
<==> string* pTitle = t.title()
string Title = (*pTitle);
 

Similar threads

I
回复
0
查看
728
import
I
I
回复
0
查看
601
import
I
顶部