c++ - 如何在 C++ 中修复 "invalid use of incomplete type"

标签 c++ oop friend friend-function

我想通过使用一个类(class)的方法在两个类(class)之间建立友元。即使我研究了不同的教程和书籍,我也无法使其发挥作用。

编辑:: 它可以在一个文件中工作,但我想将其放在单独的文件中 - 不幸的是不能这样做:

Tbase_in_memory.h:

#ifndef FRENDY_TBASE_IN_MEMORY_H
#define FRENDY_TBASE_IN_MEMORY_H

#include <iostream>
#include <string>
#include <fstream>

class base;

class Tbase_in_memory
{
public:
    Tbase_in_memory(int = 2);
    ~Tbase_in_memory();
    void read_to_arrays(base & b);

private:
    std::string *name;
    double      *price_tag;
    int         *code;
    char        *type;
    int         _size;
};

#endif

Tbase_in_memory.cpp:

#include "Tbase_in_memory.h"

using namespace std;

class base;
Tbase_in_memory::Tbase_in_memory(int s)
{
    _size = s;
    name = new string[_size];
    price_tag = new double[_size];
    code = new int[_size];
    type = new char[_size];
}

Tbase_in_memory::~Tbase_in_memory()
{
    delete[] name;
    delete[] price_tag;
    delete[] code;
    delete[] type;
}

void Tbase_in_memory::read_to_arrays(base & b)
{
    string line;
    while (getline(b.file, line)) {
        cout << line;
    }
}

base.h:

#ifndef FRENDY_BASE_H
#define FRENDY_BASE_H

#include <iostream>
#include <string>
#include <fstream>
#include "Tbase_in_memory.h"

class base
{
public:
    base(std::string = "...");
    ~base();
    friend void Tbase_in_memory::read_to_arrays(base & b);
private:
    std::fstream    file;
    std::string     f_name;
};

#endif

基础.cpp

#include "base.h"

using namespace std;

base::base(string n)
{
    f_name = n;
    file.open(f_name, ios::in);

    if (!file.good()) {
        cout << "Error";
        cout << string(38, '-');
        exit(0);
    }
}

base::~base()
{
    file.close();
}
#include <iostream>
#include "Tbase_in_memory.h"
#include "base.h"

using namespace std;

int main()
{
    base b("/home/Sempron/Desktop/code");
    Tbase_in_memory a;
    a.read_to_arrays(b);
    return 0;
}

我遇到错误:

"error: invalid use of incomplete type ‘class base’
     while (getline(b.file, line)) {". 

"forward declaration of ‘class base’
     class base;"

最佳答案

在文件 Tbase_in_memory.cpp 中,您还需要包含 base.h。然后就可以去掉cpp文件中的前向声明了。

#include "Tbase_in_memory.h"
#include "base.h"

using namespace std;

Tbase_in_memory::Tbase_in_memory(int s)
{
    //...

关于c++ - 如何在 C++ 中修复 "invalid use of incomplete type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57828578/

相关文章:

c++ - 如何用 `R CMD INSTALL` 和 `Makevars` 覆盖 `--configure-args` 的 `--configure-vars` 编译标志?

python-3.x - 在 Jupyter 中跨多个单元格拆分类函数?

Python3 - 如何从现有抽象类定义抽象子类?

c# - OO 设计 - 您在内部使用公共(public)属性还是私有(private)字段?

对于参数 ‘sender’ 到 ‘void*’,C++ 无法将 ‘1’ 转换为 ‘void* sending(void*)’

c++ - 使用 drawComplexControl 检索 QSliderHandle 图像

c++ - 在单独的插槽中删除发件人

c++ 与成员变量同名的内联友元函数

c++ - 在全局变量的析构函数中初始化 thread_local 变量是否合法?

c++ - 我真的需要为 friend operator<< 为命名空间中的类竭尽全力吗?