c++ - 常量问题

标签 c++ constants

我现在应该明白了,但我还没有明白。问题是 operator= 的参数可能是非常量,但这会破坏 std::vector::push_back 因为它使项成为 const,所以 operator= 必须接受一个 const 对象。好吧,我不确定我应该如何修改像这样工作的 this 对象。

#include <vector>
#include <map>
#include <iostream>

using namespace std;

int font[] = {0, 31, 0, 31, 0, 31, 0, 31};

class Foo {
    int size_;
    std::map<int, int> chars_;
    public:
    Foo(int *font, int size);
    unsigned int Size() const { return size_; }
    void Add(int ch);
    bool operator==(const Foo &rhv) const;
    int &operator[](int i);
    int const operator[](int i);
    Foo operator=(const Foo &rhv);
};

Foo::Foo(int *font, int size) {
    for(int i = 0; i < size; i++ ) {
        chars_[size_++] = font[i];
    }
}

bool Foo::operator==(const Foo &rhv) const {
    if(Size() != rhv.Size()) return false;
    /*for(int i = 0; i < Size(); i++ ) {
        if ( chars_[i] != *rhv[i] ) 
            return false;
    }*/
    return true;
}

int &Foo::operator[](int i) {
    return chars_[i];
}

int const Foo::operator[](int i) {
    return chars_[i];
}

Foo Foo::operator=(const Foo &rhv) {
    if( this == &rhv ) return *this;
    for(unsigned int i = 0; i < rhv.Size(); i++ ) {
        //Add(*rhv[i]);
        //chars_[size_++] = rhv[i];
    }
    return *this;
}

void Foo::Add(int ch) {
    chars_[size_++] = ch;
}

int main()
{
    vector<Foo> baz;
    Foo bar = Foo(font, 8);
    baz.push_back(bar);    
}

编辑:好吧,我又花了一些时间阅读有关 const 的内容。我想做的事有可能吗?我问的原因是因为这句话: 如果它在没有 const 限定符的情况下无法编译,并且您正在返回指向可能是对象一部分的内容的引用或指针,那么您的设计很糟糕。

我考虑到了这一点,并避免在 const 方法中返回引用。这产生了这个错误:

test.cpp:18: error: 'const int Foo::operator[](int)' cannot be overloaded
test.cpp:17: error: with 'int& Foo::operator[](int)'
test.cpp:41: error: prototype for 'const int Foo::operator[](int)' does not match any in class 'Foo'
test.cpp:37: error: candidate is: int& Foo::operator[](int)

摆脱 int & Foo::operator[] 就摆脱了那个错误。我知道我可以创建一个新的访问器来将更改应用到 chars_,但我想我会更新它并找出我正在尝试做的事情是否可行。

最佳答案

您的operator[] 非常规。在您的赋值运算符中,为什么不直接访问 rhv.chars_

例如

Foo& Foo::operator=(const Foo &rhv) {
    _size = rhv._size;
    _chars = rhv._chars;
    return *this;
}

关于c++ - 常量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1582370/

相关文章:

java - 在 Spring @RequestMapping 值中使用字符串数组 "constant"

c++ - 为错误 12029 抛出 CInternetException

c++ - 如何打开已经以独占模式打开的文件?

c++ - 不明确的虚拟继承

c++ - 如何在 C++ 编译期间去除调试代码?

java - 迭代最大化算法

php - 当包含来自远程服务器的 PHP 文件时,常量不是 "populated"

c++ - 为什么 map::iterator 导致编译错误。 C++

c++ - 将 const auto & 转换为迭代器

常量数组 const {}