[英]How to properly overload the insertion operator for a templated class that's part of a user-defined namespace?
[英]How to refer to the pointer **environ in a user-defined namespace's member function?
#include <iostream>
namespace A {
void func();
}
void A::func()
{
extern char **environ;
std::cout << environ[0] << std::endl;
}
int main()
{
A::func();
return 0;
}
像上面的代碼一樣,我只想在A::func()
使用系統定義的指針**environ
,但g ++總是說:
undefined reference to `A::environ'
如何正確使用系統定義的變量environ
?
您只需要在全局范圍內聲明environ
,這當然是在定義它的地方,而不是在您的函數中。
如果你想對它更清潔並避免不必要地使用全局變量,你可以用這種方式聲明main:
int main(int argc, char* argv[], char* envp[])
然后只需將envp
傳遞給您的函數。 它將與全球一樣有效。
加
#include <unistd.h>
和環境必須在全球范圍內。
所以代碼看起來像這樣:
#include <iostream>
#include <unistd.h>
extern char **environ;
namespace A {
void func();
}
void A::func()
{
std::cout << environ[0] << std::endl;
}
int main()
{
A::func();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.