【问题标题】:how to dereference a pointer of an object inside another object如何取消引用另一个对象内的对象的指针
【发布时间】:2015-04-06 14:39:19
【问题描述】:

我需要构建一组相互依赖的类。当我将指向一个类的指针传递给在其中实例化的另一个类时,我遇到了麻烦。

这里有一个例子来说明我的问题。

#include<iostream>
#include<vector>

using namespace std;

class base;

//

 child class
    class child
    {
    public:
    child(){};
    void setPointer (base* ptr){pointer = ptr; }
    void printing(){(*pointer).print();} // error C2027: use of undefubed type base
                                        // error C2227: '.print' must have class/struct/union
private:
    base* pointer;
};

// base class
class base
{
public:
    base()
    {
        initial_vec();
        VEC[0].setPointer(this);
        VEC[0].printing();
    }

    void print() { cout <<"printing from BASE"<< endl;}

    void initial_vec ()
    {
        child child1;
        VEC.push_back(child1);
    }

private:
    vector<child> VEC;
};

int main()
{
    base b1;

    system("pause");
    return 1;
}

您知道我如何在不出现这些错误的情况下实现这一目标吗?

提前谢谢你

【问题讨论】:

  • 您不能从内联代码中取消引用前向声明。这必须外部到一个单独的翻译单元。

标签: c++ class dereference


【解决方案1】:

看起来你得到它的错误是因为你试图从你的 base 类中调用 printing() 并且只有一个前向声明。要解决您的问题,请在完全定义 base 类之后定义函数 printing() 的主体。

Here 是关于前向声明的更多细节。

【讨论】:

    【解决方案2】:

    “你知道我如何在不出现这些错误的情况下实现这一目标吗?”

    这很简单。您省略了引用 base 的内联代码部分,并将 tem 移到类的完整声明之后:

    #include<iostream>
    #include<vector>
    
    using namespace std;
    
    class base;
    
     child class {
        public:
        child(){};
        void setPointer (base* ptr); // <<< Only declare the functions here
        void printing();
    
    private:
        base* pointer;
    };
    

    // base class
    class base {
    public:
        base()
        {
            initial_vec();
            VEC[0].setPointer(this);
            VEC[0].printing();
        }
    
        void print() { cout <<"printing from BASE"<< endl;}
    
        void initial_vec ()
        {
            child child1;
            VEC.push_back(child1);
        }
    
    private:
        vector<child> VEC;
    };
    

    在 base 完全声明后定义函数:

    void child::setPointer (base* ptr){pointer = ptr; }
    void child::printing(){(*pointer).print();}
    
    int main() {
        base b1;
    
        system("pause");
        return 1;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2023-01-19
      • 2019-05-07
      • 2015-06-17
      • 1970-01-01
      相关资源
      最近更新 更多