当对象同时又const与non-const函数时,我们传进去的参数会调用什么?
答:常量对象就调用const类型的函数,非常量对象两个都可以调用
测试代码
#include<iostream> #include<algorithm> #include<string> using namespace std; class A { private: std::string s; public: A() { s = "abcdefg"; } /* 同时存在const和non-const,调用时会调用哪个函数 */ void test(int a) const { a = 5; cout << "const" << endl; } void test(int a) { cout << "non const" << endl; } const char& operator[](int b)const { std::cout << "const" << endl; return s[b]; } char& operator[](int b) { std::cout << "non-const" << std::endl; return s[b]; } }; /* 测试cnonst与non-const */ void testConst() { A a; int b = 2; const int c = 3; a.test(2); a.test(b); a.test(c); a[2]; a[b]; a[c]; const A d; d.test(2); d.test(b); d.test(c); d[2]; d[b]; d[c]; } int main() { testConst(); }