c++ - 如何让它工作,2个类(class)的问题

标签 c++ c++11

我的小项目有问题。我有两个类(class)。 问题:

error: 'Display' was not declared in this scope

显示是一个类。这是代码:

//main.cpp
#include <iostream>
#include "Display.h"
#include "Polynomial.h"

using namespace std;

int main()
{
    Polynomial prr;
    prr.show();
    cout<<endl;
    cout<<"Enter x= ";
    int x;
    cin>>x;
    cout<<endl;

    cout<<"value for x="<<x<<endl<<"y="<<prr.value(x);

    Display aa; // this doesn't work
    //abc.show();

    return 0;
}

//Display.h
#ifndef DISPLAY_H
#define DISPLAY_H

class Display
{
    std::vector <vector <char> > graph;
    public:
        Display(int a, int b);
        //friend void lay(Polynomial abc,Display cba);
        //void show();
};

#endif // DISPLAY_H

我在想,也许 vector 正在做问题。我在没有 vector 的情况下对其进行了测试,但它并没有改变任何东西。

//Display.cpp
#include "Display.h"
#include <iostream>

using namespace std;


Display::Display(int a, int b)
{
    //ctor
    if(a%2==0)
        a++;
    if(b%2==0)
        b++;

    vector <char> help;
    vector <char> mid;

    for(int i=0; i<b; i++)
    {
        mid.push_back('-');
        if(i==(b+1)/2)
            help.push_back('|');
        else
            help.push_back(' ');
    }

    for(int i=0; i<a; i++)
    {
        if(i==(a+1)/2)
            graph.push_back(mid);
        else
            graph.push_back(help);
    }
}

现在它是 Polynomial 类,它工作正常,但 Display 类没有,我不知道为什么。

//Polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <vector>



//class Display;

class Polynomial
{...}


#endif // POLYNOMIAL_H

//Polynomial.cpp
#include "Polynomial.h"
#include <iostream>
#include <windows.h>
#include <cmath>

using namespace std;

// constructors and methods here
// everything here working fine

编辑: 经过几次尝试,我退后了一步, 现在在 Display.h 中 我有错误:

error: 'vector' does not name a type

所以我包含了 vector 库。

但这并没有帮助。

最佳答案

错误编号 1:

你定义了一个带两个参数的构造函数

Display(int a, int b);

但是当你打电话的时候

Display aa;

编译器尝试使用默认构造函数实例化 Display 对象,而您禁用了自定义构造函数的定义;

你有两种可能性:

添加一个默认的构造函数,比如

Display() = default;

Display() { /* do whatever you want to init with default parameter */}

使用您定义的构造函数实例化您的变量

Display aa{0,0};

错误编号 2:

std::vector < std::vector <char> > graph;

您声明了 vector<char>而不是 std::vector<char>

See a Live Example

关于c++ - 如何让它工作,2个类(class)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463482/

相关文章:

c++ - 增变器通过引用返回

c++ - 简单的 C++ 程序间歇性段错误

c++ - 通过引用传递 scoped_ptr 是一种好习惯(在类中从一种方法传递到另一种方法)吗?

c++ - 这个 std::vector 构造函数中发生了什么?

c++ - c++构造对象时圆括号和大括号有什么区别

c++ - 如何在 linux 中使用 Makefile 编译 tensorflow c_api

c++ - CMAKE_CXX_FLAGS 中的重复编译标志

c++ - 如果不键入别名类型的完整声明,则无法从单独文件中的类模板定义访问类型别名

c++ - 如何在 operator[] 的声明中将 decltype 应用于成员函数

c++ - 在没有阻塞的情况下开始剩余的 future