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() 函数则没有问题,因为这些函数没有修改成员变量。
788

被折叠的 条评论
为什么被折叠?



