一般类的成员变量是在构造函数中初始化,当你想改变成员变量的值,就需要使用参数,来传递。
class CFoo
{
public:
CFoo(string str);
~CFoo();
void Print()
{
cout<<"In Print(), data="<<data<<endl;
};
string data;
};
CFoo::CFoo(string str)
{
data=str;
cout<<"In Foo C Func, data="<<str<<endl;
}
CFoo::~CFoo()
{
cout<<"In Foo D Func, data="<<data<<endl;
}
这里就很典型。
CFoo::CFoo(string str)
{
data=str;
cout<<"In Foo C Func, data="<<str<<endl;
}
这里用()中的参数来为变量赋值,可以使以后data在整个类的其他地方也有了改变。这也是类的好处。一个地方改变了,整个类的其他地方,也做了相应的改变,因为类中的其他成员可以使用这个变量。 |