gpt4 book ai didi

c++ - 常量对象的函数重载

转载 作者:行者123 更新时间:2023-11-30 05:38:51 24 4
gpt4 key购买 nike

struct A {

void foo(int i, char& c) {
cout << "foo int char&" << endl;
}

void foo(int& i, int j) const {
cout << "const foo int& int" << endl;
}

};

int main() {
A a;
const A const_a;
int i = 1;
char c = 'a';
a.foo(i,i);
}

将被打印:

const foo int& int

我不明白为什么。为什么不打印“const foo int& int”?我以为constant Object只能调用constant methods,none const不能调用none const。

最佳答案

你误解了 member-const

普通对象可以调用任何成员函数,const 或其他。

约束是您的 const_a 将无法在其上调用非 const 成员函数。不幸的是,您没有对此进行测试。

关于c++ - 常量对象的函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574549/

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