#include <iostream>
class hyp
{
public:
//这里后面必须要加上const修饰符,否则这两个test函数不能重载
int const& test() const
{
std::cout << "const" << std::endl;
return num;
}
//int &test()
//{
// std::cout << "non-const" << std::endl;
// return num;
//}
int getNum()
{
return num;
}
private:
int num = 2;
};
int main()
{
hyp h;
int out = 3;
std::cout << "out value = " << out <<std::endl;
std::cout << "%%%%%%%%%%" <<std::endl;
//返回类型为non-const和const都可以用
out = h.test();
std::cout << "out value = " << out <<std::endl;
std::cout << "num value = " << h.getNum() <<std::endl;
std::cout << "%%%%%%%%%%" <<std::endl;
//返回类型为non-const和const都可以用
const int conOut = h.test();
std::cout << "conOut value = " << conOut <<std::endl;
std::cout << "num value = " << h.getNum() <<std::endl;
std::cout << "%%%%%%%%%%" <<std::endl;
//如果类中只有返回类型为const&的test函数,那么这个h.test()=4就会报错
//也就是说这里只能调用h.test()的non-const reference的返回类型,就可成功赋值
//h.test() = 4;
//std::cout << "num value = " << h.getNum() <<std::endl;
}
此时的输出为:
如果把int &test()
和 h.test() = 4;
的注释符都去掉: