我试图从“内部”(本地)类的方法访问“外部”类的属性,但失败了。
编译失败
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
你能帮我一下吗?
最佳答案
你的问题出在你的hello()
函数上。 name
在这里超出范围。它不是您的内部
类的一部分。不幸的是,您的内部类将无法看到外部类及其成员,因此:
void outer::inner::hello(){
std::cout << "Hello " << name << "\n";
}
将产生一个错误,告诉您找不到name
。
您可以执行以下操作:
#include <iostream>
#include <string>
class outer
{
public:
static std::string name;
class inner
{
public:
void hello();
};
void dostuff();
};
std::string outer::name = ""; // This is key. You need to instantiate outer's name somewhere.
void outer::inner::hello(){std::cout << "Hello " << outer::name << "\n";}
void outer::dostuff(){inner instanceInner; instanceInner.hello();}
int main()
{
outer instanceOuter;
instanceOuter.name = std::string("Alice");
instanceOuter.dostuff();
return 0;
}
输出:
Hello Alice
关于c++ - 尝试从本地类方法访问属性时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43440963/