|
发表于 2024-10-28 17:14:52
|
显示全部楼层
C++是个讲人权的地方,你想怎么样都行,但后果自负。所以我觉得,能用C则用C,能用JAVA或则用JAVA或者C#,能用脚本则用脚本,除非迫不得已,否则还是远离C++比较好。
举个例子吧,调用一个函数,这玩意简单的不能再简单了。在C++里看上去也有点复杂,你可以不那么写,但你约束不了别人怎么写。
int foo(int n)
{
int s = 1;
for(; 0 < n; --n)
s *= n;
return s;
}
class C
{
public:
C() = default;
explicit C(int a) : y(a) {}
~C() = default;
int foo(int x) const { return x + y; }
private:
int y;
};
#include <functional>
#include <string>
#include <iostream>
int main()
{
typedef int (*f_int_t1) (int); // the old style
f_int_t1 foo_p1 = &foo; // & is redundant and optional
using f_int_t2 = int (*)(int); // easy to understand
f_int_t2 foo_p2 = foo;
std::function<int(int)> stdf_foo = &foo; // modern
const std::string Sep(" ");
constexpr int N = 5;
std::cout << "global function:" << foo(N) << Sep << foo_p1(N) << Sep
<< foo_p2(N) << Sep << stdf_foo(N) << "\n";
typedef int (C::* f_C_int_t1) (int) const;
f_C_int_t1 C_foo_p1 = &C::foo; // the old style
using f_C_int_t2 = int (C::*) (int) const;
f_C_int_t2 C_foo_p2 = &C::foo;
const C c(10);
constexpr int X = 20;
std::cout << "old member call: " << (c.*C_foo_p1)(X) << Sep << (c.*C_foo_p2)(X) << "\n";
std::function<int(const C&, int)> stdf_C_foo = &C::foo;
auto greet = std::mem_fn(&C::foo);
auto callback = std::bind(&C::foo, &c, std::placeholders::_1);
std::cout << "new member call: " << stdf_C_foo(c, X) << Sep << greet(c, X) << Sep
<< callback(X) << "\n";
return 0;
} |
|