const在C++中的一些应用

---恢复内容开始---

const在C++中的一些用法

When modifying a data declaration, the const keyword specifies that the object or variable is not modifiable.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it.
这格式MDN上对const的定义,大概的意思就是const用在不能被改变的变量声明中,而且加const的话,编译器不会改变其值。

通俗易懂的讲,只要这个变量不会被修改,就要加const,,,,,有时候不加const的话会出错,尤其是在写拷贝构造的时候,,,,这个在说明编译器害怕你搞事,,,,哈哈,不需要太正式的表达,这样会记住的更好。

const的基础语法

const declaration ;
member-function const;
也就是在变量声明之前,在函数声明之后

这个有利说明了const以后是不能修改变量值得。

// constant_member_function.cpp  
class Date  
{  
public:  
   Date( int mn, int dy, int yr );  
   int getMonth() const;     // A read-only function  
   void setMonth( int mn );   // A write function; can't be const  
private:  
   int month;  
};  

int Date::getMonth() const  
{  
   return month;        // Doesn't modify anything  
}  
void Date::setMonth( int mn )  
{  
   month = mn;          // Modifies data member  
}  
int main()  
{  
   Date MyDate( 7, 4, 1998 );  
   const Date BirthDate( 1, 18, 1953 );  
   MyDate.setMonth( 4 );    // Okay  
   BirthDate.getMonth();    // Okay  
   BirthDate.setMonth( 4 ); // C2662 Error  
}  

只读函数才能写cosnt,只读函数包括类中的拷贝构造等。

猜你喜欢

转载自www.cnblogs.com/Abudlla/p/9157377.html