C++类与const关键字

C++类与const关键字

有时候为了避免误操作而修改了一些人们不希望被修改的数据,此时就必须借助 const 关键字加以限定了。借助 const 关键字可以定义 const 类型的成员变量、成员函数、常对象以及对象的常引用。

const 对象定义的基本语法如下:
const 类名 对象名(实参名);
类名 const 对象名(实参名);
#include<iostream>
using namespace std;

class book
{
public:
    book(){}
    book(book &b);
    book(char* a, double p = 5.0);
    void setprice(double a);
    double getprice()const;
    void settitle(char* a);
    char * gettitle()const;
    void display()const;
private:
    double price;
    char * title;
};

book::book(book &b)
{
    price = b.price;
    title = b.title;
}

book::book(char* a, double p)
{
    title = a;
    price = p;
}

void book::display()const
{
    cout<<"The price of "<<title<<" is $"<<price<<endl;
}

void book::setprice(double a)
{
    price = a;
}

double book::getprice()const
{
    return price;
}

void book::settitle(char* a)
{
    title = a;
}

char * book::gettitle()const
{
    return title;
}

int main()
{
    const book Alice("Alice in Wonderland",29.9);
    Alice.display();
    Alice.setprice(51.0);//compile error
    return 0;
}

main.cpp:61: error: passing ‘const book’ as ‘this’ argument discards qualifiers [-fpermissive] Alice.setprice(51.0);//compile error

程序设计过程中要求修改常对象中的某个成员变量,这个时候如果是普通的成员变量是不能被修改的。为了满足这一需求,C++ 提供了 mutable 关键字。
mutable int var;

对象的const引用

#include<iostream>
using namespace std;

class book
{
public:
    book(){}
    book(book &b);
    book(char* a, double p = 5.0);
    void setprice(double a);
    double getprice()const;
    void settitle(char* a);
    char * gettitle()const;
private:
    double price;
    char * title;
};

book::book(book &b)
{
    price = b.price;
    title = b.title;
}

book::book(char* a, double p)
{
    title = a;
    price = p;
}

void book::setprice(double a)
{
    price = a;
}

double book::getprice()const
{
    return price;
}

void book::settitle(char* a)
{
    title = a;
}

char * book::gettitle()const
{
    return title;
}

void display(const book &b)
{
    b.setprice(59.9);  //compile error
    cout<<"The price of "<<b.gettitle()<<" is $"<<b.getprice()<<endl;  //ok
}

int main()
{
    book Alice("Alice in Wonderland",29.9);
    display(Alice);
    book Harry("Harry potter", 49.9);
    display(Harry);
    return 0;
}

main.cpp:53: error: passing ‘const book’ as ‘this’ argument discards qualifiers [-fpermissive]
b.setprice(59.9); //compile error

我们将 display() 函数声明为顶层函数,其函数形参为 book 类对象的常引用,在函数内部我们首先调用 public 属性的 setprice() 函数,企图修改 price 成员变量,编译无法通过。而在其后调用 gettitle() 和 getprice() 函数则没有问题,因为这些函数没有修改成员变量。

reference

微学苑 C++ const

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

静思心远

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值