gpt4 book ai didi

c++ - 具有所有属性 const 的类是否也需要将成员函数声明为 const?

转载 作者:太空狗 更新时间:2023-10-29 20:59:56 24 4
gpt4 key购买 nike

标题已经说明了一切。尽管如此,让我稍微扩展一下:我的类的所有属性都是 const:

template< class perm  = Perm16 >
class PermutationGroup {
public:
using StrongGeneratingSet = std::vector< std::vector< perm > >;

const std::string name;
const uint64_t N;
const StrongGeneratingSet sgs;
PermutationGroup(std::string name, uint64_t N, StrongGeneratingSet sgs) :
name(name), N(N), sgs(sgs) { assert(check_sgs()); };

bool check_sgs() const; // defined as const
bool is_canonical(vect v) const; // defined as const

[...]

};

将所有成员函数也定义为 const 有什么用吗?还是我在不必要地重复自己?

最佳答案

如果您没有将成员函数声明为const,则不能在const 对象或const 引用 引用的对象上调用它们>。例如,以下将不起作用:

const PermutationGroup& group = PermutationGroup("foobar", 42, ...);
group.check_sgs(); // ERROR: can't invoke non-const function on const objects

关于c++ - 具有所有属性 const 的类是否也需要将成员函数声明为 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com