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,请读者自己思考

猜你喜欢

转载自blog.csdn.net/u013749051/article/details/80767812
今日推荐