指向对象的常指针,指向常对象的指针

指向对象的常指针变量(指针不能在赋予新的地址)

#include <iostream>

using namespace std;

int main() {
    class ss {
        int num;
        char n;
    public:
        ss(int x, char c) : num(x), n(c) {};

        void hanshu() {
            cout << num;
        }

    };
    class student {
        int m;
        int c;
    public:
        student(int x, int y) : m(x), c(y) {}

        void func() {
            m=55;
            cout << m + 5 << endl;
        }

        void func1() const {
            cout << "fdsadf" << endl;
        }
    };
    ss s1(454,'a');
    ss *const p=&s1;类名 *const 指针名=&对象名;
    ss s2(56,'s');
    p=&s2;//false 常指针只能赋值一次
    return 0;
}

指向(常对象)的指针变量

#include <iostream>

using namespace std;

int main() {
    class student {
        int shu;
        int han;
    public:
        student(int x) {
            shu = x;
            han = 0;
        }
        student(int x, int y) : shu(x), han(y) {};
        void output() const{
            cout<<shu<<" "<<han;
        };
    };
    const student s3(45,56);
    const student s1(45);
    const student*p2=&s1;
    //对于常变量,只能用定义为指向常变量的指针const 类型 *指针变量名 指向常变量
    //指向长变量的指针还可以指向尚未定义的const 变量。
    (*p2).output();
    p2=&s3;
    (*p2).output();
    return 0;
}

函数形参数const 非const区别

#include <iostream>

using namespace std;
class student {
public:
    int shu;
    int han;
public:
    student(int x) {
        shu = x;
        han = 0;
    }

    student(int x, int y) : shu(x), han(y) {};

    void output() const {
        cout << shu << " " << han;
    };
};
//const 指针形参,则在函数调用内,不能改变指针所指向对象的值。如果是对象则不能修改数据成员值。
void func2(const  student *p )
{
    //
    (*p).shu=18;
    (*p).output();
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务