您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> C/C++ >> 求助,类嵌套,不可以用const修饰

求助,类嵌套,不可以用const修饰

来源:网络整理     时间:2016/8/31 13:37:28     关键词:

关于网友提出的“ 求助,类嵌套,不可以用const修饰”问题疑问,本网通过在网上对“ 求助,类嵌套,不可以用const修饰”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: 求助,类嵌套,不可以用const修饰
描述:

练习模版类时候,发现一个问题,很是疑惑
写了一个嵌套的类,同样是重载操作符,在嵌套的类中使用,若加上const,就会编译错误,不加不错.
错误信息:
passing 'const myvector<10, int>' as 'this' argument of 'Type& myvector::operator[](int) [with int n = 10, Type = int]' discards qualifiers|
||=== 已完成构建: 1 个错误, 0 个警告 ===|

template 
class myvector                 
{
private:
    Type te[n];
public:
    myvector()
    {
        for(int i=0;i<>
    }
    Type &operator [](int in)
    {
        if(in>-1&&in<>
            return te[in];
        else
            return te[n-1];
    }
    void show() const//此处可以加上
    {
        for(int i=0;i<>
            cout<<>
        return;
    }
};
template 
class mycontainvector 
{
private:
    myvector v1;
public:
    void show() //加上const编译错误
    {
        for(int i=0;i<><>
        return;
    }
};

谢谢大家


解决方案1:

这是因为你的myvector没有重载operator[] const

解决方案2:

Type &operator [](int in)//修改成下面这种
const Type &operator [](int in)const
因为你下面的类的show如果是const成员函数,那么就不能修改成员函数,也就是说你的成员会转为const。
但是Type &operator [](int in)这句却返回了一个普通的成员,而非const,所以就冲突了。
const Type &operator [](int in)改成这种也是有问题的,因为const对象只能调用const成员函数,编译器不信任人为的保证(就是函数里的确没有修改),只相信强制的保证。所以必须是const Type &operator [](int in)const
至于const的文章我找找看。
以上介绍了“ 求助,类嵌套,不可以用const修饰”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3681887.html

相关图片

相关文章