【发布时间】:2020-03-25 18:04:41
【问题描述】:
我正在尝试填充一个向量,该向量采用我定义的多种类型的参数。但是,尽管添加了向量库并使用命名空间 std,但我收到了无效的模板参数错误。是因为我试图把我定义的类名?我应该使用另一种方法来合并我的不同数组吗?这是我的相关头文件和 cpp 文件。代码读取网表文件(文本文件)并应返回包含组件信息的向量。请帮忙。
hpp 文件:
#ifndef NETLISTREADER_HPP_
#define NETLISTREADER_HPP_
#include <vector>
#include <iostream>
#include "Resistor.hpp"
#include "Capacitor.hpp"
#include "Voltage.hpp"
#include "Opamp.hpp"
using namespace std;
vector <Resistor, Capacitor, Opamp> NetlistReader;
#endif /* NETLISTREADER_HPP_ */
cpp 文件:
#include <iostream>
#include <string>
#include <fstream>
#include <istream>
#include <cstring>
#include <vector>
#include "Resistor.hpp"
#include "Capacitor.hpp"
#include "Voltage.hpp"
#include "Opamp.hpp"
using namespace std;
vector <Resistor, Capacitor, Opamp> NetlistReader() {
ifstream netlist("C:\\Users\\lenovo\\Desktop\\BassmanNetlist.txt");
if (!netlist.is_open())
{
std::cerr << "Failed to open netlist.txt." << std::endl;
}
int n=0;
int maxnode=0;
string str;
string componentName;
int node1;
int node2;
double value;
int Rcounter=0;
int Ccounter=0;
int Ocounter=0;
while(getline(netlist,str)){
netlist >> componentName >> node1 >> node2 >> value;
maxnode= max(node1,node2);
n=max(n,maxnode);
switch(componentName[0]){
case 'R':
Rcounter++;
break;
case 'C':
Ccounter++;
break;
case 'O':
Ocounter++;
break;
}
}
cout<< "n is "<<n<<endl;
Capacitor C[Ccounter]={};
Resistor R[Rcounter]={};
Opamp O[Ocounter]={};
int counter_R=0;
int counter_C=0;
int counter_O=0;
while(getline(netlist,str)){
netlist >> componentName >> node1 >> node2 >> value;
switch(componentName[0]){
case 'R':
R[counter_R]=Resistor(node1,node2,value);
counter_R++;
break;
case 'C':
C[counter_C]=Capacitor(node1,node2,value);
counter_C++;
break;
case 'O':
O[counter_O]=Opamp(node1,node2,value);
break;
}
}
vector<Resistor,Capacitor, Opamp> NetlistReader;
NetlistReader.push_back(R);
NetlistReader.push_back(C);
NetlistReader.push_back(O);
return NetlistReader;
}
谢谢!
【问题讨论】:
-
vector只能保留一种类型的对象。如果您需要在向量中存储多种类型,请使用std::vector<std::variant<list of possible types>>,但由于您是初学者,这对您来说可能很难使用。 -
因为我使用的是vector
vectorName; synthax 我可以这样写,没有变体。在这种情况下,使用变体 dis 不能为我修复错误。 -
您没有“使用矢量
”,因为这是格式错误(非法)。
标签: c++ vector invalid-argument