c++常量_常对象_常成员函数

常量

c++中定义常量的方法相对c有些不一样。

#define PI 3.14159//for c
const int pi=3.14159;//for c++

常对象

常对象就是定义为常量的对象,如下:

const Object obj1;
Object obj1;
const Object& obj2=obj1;
Object& operator=(const Object& obj){
//code...
return *this;
}

常对象由于不能改变成员变量,因此只能调用 常成员函数,否则报错。
但常对象仍然可以访问公有成员变量,可以读取而不能修改

常成员函数

常成员函数就是类定义中被定义为const 的函数,其特点是:只可读取类的常量、变量而不能改变。

class Vector3 {
public:
    Vector3() {}
    Vector3(int x, int y, int z) :x(x), y(y), z(z) {}
    int x, y, z;
    int getX() const {//常成员函数,如果不加const,那么常对象将不能使用该函数,如下:
        return x;
    }
    void setX(int n){
        x = n;
    }
};
void myfun(const Vector3& v) {
    cout << v.getX() << endl;//报错:对象含有与成员 函数 "Vector3::getX" 不兼容的类型限定符
}

其它

基本就这么多。
需要注意的是:临时变量、局部变量的传送可以通过以下方式:
void myfun(Object obj){}//老祖宗的方法,复制一个对象副本,即值传递
void myfun(const Object obj){}//复制一个对象副本,并令其为常对象
void myfun(const Object& obj){}若对象为临时变量,则复制一个对象副本,并令其为常对象,若不是,则引用
const Object& myfun(){Object obj;return obj;}//若对象为局部变量,复制一个对象副本,并令其为常对象,若不是,则返回引用
const Object myfun(){Object obj;return obj;}//复制一个对象副本,并令其为常对象
Object myfun{Object obj;return obj;}//老祖宗的方法,复制一个对象副本,即值传递

eg.

若有以下类和函数

#include<iostream>
#include<sstream>
using namespace std;
class Vector3 {
public:
    Vector3() {}
    Vector3(int x, int y, int z) :x(x), y(y), z(z) {}
    int x, y, z;
    int getX() {
        return x;
    }
    void setX(int n){
        x = n;
    }
};
Vector3 myfun1() {
    return Vector3(1, 2, 3);
}
const Vector3 myfun2() {
    return Vector3(1, 2, 3);
}
const Vector3& myfun3() {
    return Vector3(1, 2, 3);
}

以下主函数的结果:

    cout << myfun1().getX() << endl;//ok
    cout << myfun2().getX() << endl;//报错,因为返回常对象
    cout << myfun3().getX() << endl;//报错,因为返回常对象

    Vector3 v2 = myfun2();
    Vector3 v3 = myfun3();
    cout << v2.getX() << endl;//ok,请读者自己思考
    cout << v3.getX() << endl;//ok,请读者自己思考
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值