C++ const class

C++ const class

编码文章call10242025-05-22 9:47:3112A+A-

你提供的代码存在一个问题,在 Solution 类中定义了两个同名且参数列表相同的 func 函数,只是一个为普通成员函数,另一个为 const 成员函数。这在语法上虽然允许,但在代码理解和使用上可能会造成混淆。不过从代码逻辑上来说,这两个函数会根据调用对象是否为 const 来决定调用哪一个。

以下是对代码的简单分析:

  • 当调用 const 对象 a 的 func 函数时,会调用 const 版本的 func 函数,输出 func2。
  • 当调用非 const 对象 b 的 func 函数时,会调用非 const 版本的 func 函数,输出 func1。

代码本身编译和运行是没有问题的,但为了代码的可读性和可维护性,建议避免在同一个类中定义过多同名且参数列表相同的函数。如果你有其他需求,比如对代码进行功能扩展或者优化,可以详细说明。

以下是你提供的代码,供你参考:

cpp

#include <pthread.h>
#include <iostream>
#include <thread>
#include <condition_variable>
#include <deque>
#include <atomic>
#include <memory>
#include <vector>
#include <unordered_set>
#include <iterator>
#include <algorithm>

using namespace std;

class Solution {
public:
    Solution(int a, int b) {

    }
    void func() {
        cout << "func1" << endl;
    }

    void func() const {
        cout << "func2" << endl;
    }
};


int main() {
    const Solution a(1,2);
    a.func();

    Solution b(1,2);
    b.func();
    return 0;
}
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4