我需要將函數指針傳遞給int。 現在,如果我想通過5我在做這樣的:指向int的指針。 C++
int * i = NULL;
int b = 5;
i = &b;
有沒有更好的方式來寫它更短?
我想在我詮釋這個函數傳遞是字節:
void Write2Asm(void* pxAddress, BYTE * MyBytes, int size)
我需要將函數指針傳遞給int。 現在,如果我想通過5我在做這樣的:指向int的指針。 C++
int * i = NULL;
int b = 5;
i = &b;
有沒有更好的方式來寫它更短?
我想在我詮釋這個函數傳遞是字節:
void Write2Asm(void* pxAddress, BYTE * MyBytes, int size)
爲什麼要創建一個指針變量?你爲什麼不能這樣做?
int b = 5;
func(&b)
void f(int *i)
{
//...
}
int b = 5;
f(&b);
就足夠了!
有幾個舊的C的API,總是由指針帶參數的,即使它們是有效只讀布爾值等等。我不推薦它 - 更多利息的緣故 - 但如果你想要去的整個生豬你可以做喜歡的事的hackish:
#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";
}
關鍵的是,臨時工是有效的,直到函數調用f(...)
退出之後。
@Hooch而不是Null你應該考慮使用nullptr - 它是std。 – 2011-03-10 07:14:35
也許我錯過了一些東西,但是這樣做有什麼問題:'int i = 5; FUNC?(&i);' – OneOfOne 2011-03-10 07:16:29
@Hooch我知道這「只是」一個字眼,但我相信這是很重要的:你不及格五,幹嘛做的是你傳遞**變量的地址**碰巧具有價值五位。 – 2011-03-10 07:18:39