C++中使用const对象引用做形参
在C++中可以传对象引用,比用指针方便,但是为了避免在函数中对象被修改,需要加const限定符,相应的,在实现对象的成员函数时,也要添加cosnt,这样,因为只有cosnt成员函数才能被const对象调用
注意下面的函数test,里面调用了类A的get_name和get_path,所以get_name和get_path必须是const的,而get_path1不需要是const的
#i nclude <string.h>
#i nclude <string>
#i nclude <iostream>
using namespace std;
class A
{
private:
string name;
string path;
public:
A(string _name,string _path){this->name=_name;this->path=_path;};
const string get_name() const {return this->name;};
string get_path() const {return this->path;};
};
void test(const A& testa)
{
cout<<\"A::name:\"<<testa.get_name()<<endl;
cout<<\"A::path:\"<<testa.get_path()<<endl;
}
int main()
{
A a(\"test\",\"path\");
test(a);
return 1;
}
顶(0)
踩(0)
上一篇:C++中结构体的的慨念和使用方法
下一篇:C++基础知识:成员函数的特性
- 最新评论
