c++ - 尝试从本地类方法访问属性时出现编译错误

标签 c++ class compiler-errors local

我试图从“内部”(本地)类的方法访问“外部”类的属性,但失败了。

编译失败

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/

相关文章:

c++ - CMD 异常处理 C/C++

java - 在类中创建类的实例

C++ 继承类具有同名成员

c++ - 模板化 ctor 上的编译器错误(这是编译器错误吗?)

c++ - C++ 中的 “Undefined symbols” 错误

c++ - 在运行时决定一个应用程序属于控制台/windows 子系统

c++ - 调整VS2010和VS6编译器和链接器开关以进行旧式构建

c - 在 Fortran 代码中使用 Metis 库...基础知识

c++ - 在C++ Builder 10.3中使用ENet会导致“在命名空间std中没有名为'strftime'的成员”的问题

java - 如何找到给定类名的包名?