【发布时间】:2017-09-12 10:48:39
【问题描述】:
我试图从“内部”(本地)类的方法访问“外部”类的属性,但失败了。
编译失败
class outer
{
public:
std::string name;
class inner
{
public:
void hello();
};
void dostuff();
};
void outer::inner::hello(){std::cout << "Hello " << name << "\n";}
void outer::dostuff(){inner instanceInner; instanceInner.hello();}
int main()
{
outer instanceOuter;
instanceOuter.name = std::string("Alice");
instanceOuter.dostuff();
return 0;
}
编译错误:
9:21: error: invalid use of non-static data member 'outer::name'
21:53: error: from this location
我真的不希望name 成为一个静态成员,但我并不介意我的特定目的outer 是一个单身人士。所以我尝试了static std::string name; 并得到了
编译错误:
/tmp/ccqVKxC4.o: In function `outer::inner::hello()':
:(.text+0x4b): undefined reference to `outer::name'
/tmp/ccqVKxC4.o: In function `main':
:(.text.startup+0x1f): undefined reference to `outer::name'
collect2: error: ld returned 1 exit status
你能帮帮我吗?
【问题讨论】:
标签: c++ class compiler-errors local