我的小项目有问题。我有两个类(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>
关于c++ - 如何让它工作,2个类(class)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54463482/