如果确信一个成员函数不用修改它的对象,就可以声明它为const,这样就可以作用于他的const对象了.因为const对象只能调用它的const方法.

 template<class T> class Vector
{
public:
int length() const//如果这里没有const,那么该程序会运行失败,因为padded_length的方法中的参数是const的.
{
return ;
};
int length(int);
};
template<class T>
int padded_length(const Vector<T>&v,int n)
{
int k = v.length();
return k>n?k:n;
}
int main(int argc,char* argv[])
{
Vector<int> a;
cout<<padded_length(a,)<<endl;
return ;
}

记得适当的声明成员函数为const.的更多相关文章

  1. const成员函数和const对象

    从成员函数说起 在说const成员函数之前,先说一下普通成员函数,其实每个成员函数都有一个隐形的入参:T *const this. int getValue(T *const this) { retu ...

  2. 成员函数的const到底修饰的是谁

    demo <pre name="code" class="cpp">class Test { public: const void OpVar(in ...

  3. 成员函数的const究竟修饰的是谁

    demo <pre name="code" class="cpp">class Test { public: const void OpVar(in ...

  4. 成员函数的const不能被修改,包括指针

    #include <iostream> class A { private: std::string a; public: A(std::string b) :a(b){} const c ...

  5. C++中的const成员函数(函数声明后加const,或称常量成员函数)用法详解

    http://blog.csdn.net/gmstart/article/details/7046140 在C++的类定义里面,可以看到类似下面的定义: 01 class List { 02 priv ...

  6. c++ const 成员函数

    第一个事实: 某类中可以这么声明定义两个函数,可以重载(overload) void pa(){ cout<<"a"<<endl; } void pa() ...

  7. c++ 学习之const专题之const成员函数

    一些成员函数改变对象,一些成员函数不改变对象. 例如: int Point::GetY() { return yVal; } 这个函数被调用时,不改变Point对象,而下面的函数改变Point对象: ...

  8. C++ Const成员函数

    一些成员函数改变对象,一些成员函数不改变对象. 例如:  int Point::GetY() { return yVal; }  这个函数被调用时,不改变Point对象,而下面的函数改变Point对象 ...

  9. c++中的const参数,const变量,const指针,const对象,以及const成员函数

    const 是constant 的缩写,“恒定不变”的意思.被const 修饰的东西都受到强制保护,可以预防意外的变动,能提高程序的健壮性.所以很多C++程序设计书籍建议:“Use const whe ...

随机推荐

  1. LeetCode OJ:Largest Number(最大数字)

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  2. LeetCode OJ:Subsets(子集)

    Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must ...

  3. 面试题12:打印1到最大的n位数

    题目:输入数字n,按顺序打印出从1最大的n位十进制数.比如输入3,则打印出1.2.3一直到最大的3位数即999. 考点:大数问题. 解决方案:在字符串上模拟数字加法. <剑指Offer>上 ...

  4. 如何选择MySQL数据库的安装方式

     MySQL数据库安装有yum安装,rpm安装,二进制编译安装,cmake,或者make安装,但是选择什么样的安装方式则全看实际应用场景. 下为网友总结安装方式选择:   若是对数据库要求不太高的场景 ...

  5. memcached数据库

    Python-memcached的基本使用

  6. CodeForces - 827A:String Reconstruction (基础并查集)

    Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun ...

  7. LeetCode 340. Longest Substring with At Most K Distinct Characters

    原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/ 题目: Give ...

  8. 普通平衡树 - Treap

    怕被学弟怼 : "你的博客上没有Treap模板啊?" #include <cstdio> #include <cstring> #include <a ...

  9. Yii的常用URL和渲染方法

    当前页面url  Yii::app()->request->url;跳转前一个页面url $this->redirect(Yii::app()->request->url ...

  10. 微信无法跳转appstore总结--应用宝微下载申请

    以前是有方法,可以实现微信下跳转appstore的. 大概就是把url改为:http://mp.weixin.qq.com/mp/redirect?url="跳转url"(可编码也 ...