gpt4 book ai didi

c++ - 包装一个对象并假装它是一个int

转载 作者:行者123 更新时间:2023-12-02 09:50:21 25 4
gpt4 key购买 nike

我有一个想使用的Object类,好像它是int一样。换句话说,我想将此对象传递给接受intint*int&的函数,以便函数“仅”看到包装的int值。

下面的代码说明了我想做什么。我能够编写intint*的代码,但无法编写int&的代码。

#include <cassert>   

class Object
{
public:
int bla = 0;
int val = 0; // the int being wrapped

Object(int v) : val(v) {};
operator int() const { return val; };
int *operator &() { return &val; };

#if 1
int & operator() { return val; }; // << does not compile
#endif
};

int func(int val) {
return val * 2;
}

void Bar(int* pval, int val) {
*pval = val;
}

void Foo(int & pval, int val) {
pval = val;
}

int main() {
int val;
Bar(&val, 123);
assert(val == 123);
Foo(val, 789);
assert(val == 789);

Object o(8);
assert(func(o) == 2 * 8); // operator int()
Bar(&o, 1234); // int *operator &()
assert(o.val == 1234);

#if 1
Foo(o, 456); // << does not compile
assert(o.val == 456);
#endif
}

如果将 #if 1替换为 #if 0,则代码将按预期工作。

有人可以指出我正确的方向,以便 Foo(o, 456);编译吗?

最佳答案

问题是转换运算符,您使用了错误的语法。

它应该是

operator int&() { return val; }

关于c++ - 包装一个对象并假装它是一个int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60222734/

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