菜菜

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <iostream>
using namespace std;

class MyClass
{
    public:
        int x;
        static int n;
        const int y;
        MyClass(int val)
                : x(val), y(20)
        {
        }
//        int get()
//        {
//            return x;
//        }
        //int get() const {return x;}        // const member function
        //const int& get() {return x;}       // member function returning a const&
        //const int& get() const {return x;} // const member function returning a const&
        int get()
        {
            return x;
        }
        int gett() const
        {
            n++;
            return y;
        }
        int getY()
        {
            cout<<"非成员函数常量getY"<<endl;
            return y;
        }
        int getY() const
        {
            cout<<"常量成员函数getY"<<endl;
            return y;
        }
        //return const int&
        //只要不修改对象的状态就是合法的
//        int& getYYYY()
//        {
//            //错误,返回对象常量的引用给外部
//            return y;
//        }
//        int& getYYYY() const
//        {
//            //错误,返回对象常量的引用给外部,改成常量成员函数还是非法
//            return y;
//        }
        //返回常量引用
        const int& getXX()
        {
            return x;
        }
        //常量成员函数返回常量引用
        const int & getXXX() const
        {
//            错误,改变了对象的状态
//            x++;
            return x;
        }
        //成员函数返回一个常量引用
        const int& getYY()
        {
            //错误
//            y++;
//            正确
//            x++;
            return y;
        }
        //返回值,合法
        int getYYY()
        {
            return y;
        }
        //判断是否合法,只要判断是否改变了对象的状态,比如对象的成员是常量,但是返回引用给外部
        //常量成员函数是否改变了对象的状态

};
int MyClass::n = 0;
/**
 * 常量对象只能调用常量成员函数,所以上面的get不能从foo对象调用
 */
/**
 *
 * Member functions specified to be const cannot modify non-static data members nor call other non-const member functions.
 * In essence, const members shall not modify the state of an object.
 * 指定成const的成员函数不能修改非静态数据成员,也不能调用非常量成员函数,从本质上来说,常量成员不能修改对象的状态
 */
/**
 *const objects are limited to access only member functions marked as const,
 *but non-const objects are not restricted and thus can access both const
 *and non-const member functions alike.
 *常量对象被限制能只允许调用标记成常量的成员函数,但是非常量对象没有这么严格,因此允许它调用常量和非常量成员函数.
 *
 */
int main()
{
    const MyClass foo(10);
    MyClass bar(10);
// foo.x = 20;            // not valid: x cannot be modified
    cout << foo.x << '\n';  // ok: data member x can be read
    int y = foo.gett();
    cout << "y=" << y << endl;
    cout << "n=" << MyClass::n << endl;
    cout<<"getY"<<foo.getY()<<endl;
    cout<<"getY"<<bar.getY()<<endl;
    cout<<MyClass::n<<endl;
    return 0;
}

 

posted on 2018-02-14 23:04  好吧,就是菜菜  阅读(157)  评论(0编辑  收藏  举报