相关疑难解决方法(0)

如何删除类似const和非const成员函数之间的代码重复?

假设class X我想要返回内部成员的访问权限:

class Z
{
    // details
};

class X
{
    std::vector<Z> vecZ;

public:
    Z& Z(size_t index)
    {
        // massive amounts of code for validating index

        Z& ret = vecZ[index];

        // even more code for determining that the Z instance
        // at index is *exactly* the right sort of Z (a process
        // which involves calculating leap years in which
        // religious holidays fall on Tuesdays for
        // the next thousand years or so)

        return ret;
    }
    const …
Run Code Online (Sandbox Code Playgroud)

c++ const class code-duplication c++-faq

228
推荐指数
11
解决办法
3万
查看次数

复制,常量和非常量,吸气剂的优雅解决方案?

你有没有恨它

class Foobar {
public:
    Something& getSomething(int index) {
        // big, non-trivial chunk of code...
        return something;
    }

    const Something& getSomething(int index) const {
        // big, non-trivial chunk of code...
        return something;
    }
}
Run Code Online (Sandbox Code Playgroud)

我们无法使用另一个方法实现这两种方法,因为您无法constconst版本中调用非版本(编译器错误).演员将被要求const从非const一个版本调用该版本.

有没有一个真正优雅的解决方案,如果没有,最接近一个?

c++ const

114
推荐指数
4
解决办法
5万
查看次数

常量和不带相同的功能 - 何时以及为何?

T& f() { // some code ... }
const T& f() const { // some code ... }
Run Code Online (Sandbox Code Playgroud)

我现在已经看过几次了(在我迄今为止研究的介绍性书中).我知道第一个const使返回值为const,换句话说:不可修改.我相信第二个const允许为const声明的变量调用该函数.

但是为什么你会在同一个类定义中同时拥有这两个函数?编译器如何区分这些?我相信第二个f()(带const)也可以调用非const变量.

c++ const

31
推荐指数
4
解决办法
5556
查看次数

为什么有const和非const访问器?

为什么STL容器定义访问器的const和非const版本?

定义const T& at(unsigned int i) constT& at(unsigned int)不仅仅是非const版本有什么好处?

c++ getter const

4
推荐指数
1
解决办法
991
查看次数

标签 统计

c++ ×4

const ×4

c++-faq ×1

class ×1

code-duplication ×1

getter ×1