C++ 指向int.C+的指针+;
我需要传递到int的函数指针。 现在,如果我想通过5级考试,我会这样做:C++ 指向int.C+的指针+;,c++,pointers,int,C++,Pointers,Int,我需要传递到int的函数指针。 现在,如果我想通过5级考试,我会这样做: int * i = NULL; int b = 5; i = &b; 有没有更好的方法把它写得更短 我想将I int中的字节传递到此函数: void Write2Asm(void* pxAddress, BYTE * MyBytes, int size) 您可以将&b传递给函数;不需要中间指针变量。为什么要创建指针变量?。你为什么不能这样做 int b = 5; func(&b) 够了 有一些旧的C
int * i = NULL;
int b = 5;
i = &b;
有没有更好的方法把它写得更短
我想将I int中的字节传递到此函数:
void Write2Asm(void* pxAddress, BYTE * MyBytes, int size)
您可以将&b传递给函数;不需要中间指针变量。为什么要创建指针变量?。你为什么不能这样做
int b = 5;
func(&b)
够了 有一些旧的C API总是通过指针获取参数,即使它们实际上是只读布尔值等等。。我不推荐它——更多是为了兴趣——但如果你想全力以赴,你可以做一些粗俗的事情,比如:
#include <iostream>
struct X
{
X(int n) : n_(n) { std::cout << "X()\n"; }
~X() { std::cout << "~X()\n"; }
operator int&() { return n_; }
operator const int() const { return n_; }
int* operator&() { return &n_; }
const int* operator&() const { return &n_; }
int n_;
};
// for a function that modifies arguments like this you'd typically
// want to use the modified values afterwards, so wouldn't use
// temporaries in the caller, but just to prove this more difficult
// case is also possible and safe...
void f(int* p1, int* p2)
{
std::cout << "> f(&" << *p1 << ", &" << *p2 << ")\n";
*p1 += *p2;
*p2 += *p1;
std::cout << "< f() &" << *p1 << ", &" << *p2 << "\n";
}
int main()
{
// usage...
f(&X(5), &X(7));
std::cout << "post\n";
}
#包括
结构X
{
x(int n):n{(n){sd::couth-HooCH,而不是NULL,您应该考虑使用NulLPTR——它是STD。可能我丢失了一些东西,但是做了什么错误:<代码> int i=5;FUNC(& i);< /Cord>?@ HooCH,我知道它是“公正的”。一个措辞,但我认为它很重要:你没有传递5,你所做的是传递一个恰好值为5的变量的地址。nullptr
还不是标准的。作为“最新的std”,不需要使用nullptr
。“传统的”路不会走到任何地方。还有一个问题。我可以使用(PBYTE)&I其中int I=5。函数真的需要指向bytes@Hooch:当然可以,你能做到。
#include <iostream>
struct X
{
X(int n) : n_(n) { std::cout << "X()\n"; }
~X() { std::cout << "~X()\n"; }
operator int&() { return n_; }
operator const int() const { return n_; }
int* operator&() { return &n_; }
const int* operator&() const { return &n_; }
int n_;
};
// for a function that modifies arguments like this you'd typically
// want to use the modified values afterwards, so wouldn't use
// temporaries in the caller, but just to prove this more difficult
// case is also possible and safe...
void f(int* p1, int* p2)
{
std::cout << "> f(&" << *p1 << ", &" << *p2 << ")\n";
*p1 += *p2;
*p2 += *p1;
std::cout << "< f() &" << *p1 << ", &" << *p2 << "\n";
}
int main()
{
// usage...
f(&X(5), &X(7));
std::cout << "post\n";
}