【问题标题】:Outputting a class function from class object held in a vector从向量中保存的类对象输出类函数
【发布时间】:2015-02-21 01:51:59
【问题描述】:

对于我的 C++ 类中的一个项目,我必须将一些形状类对象保存到一个向量中,然后稍后使用它们来返回这些形状的区域。我的类运行良好,但我不知道如何恢复到任何旧的类对象,以便稍后在程序中使用它们。在我需要将该区域保存到另一个文本文件的地方,我只是找不到在发送之前从向量中获取正确结果的方法。

#include <iostream>
#include <fstream>
#include <vector>
#include "Shape.h"
#include "Triangle.h"
#include "Rect.h"


using namespace std;

int main()
{
    ifstream inFS;
    double a = 0;
    double b = 0;
    double c = 0;
    vector <Rect> vRect;
    vector <Triangle> vTriangle;

    Rect Rect;
    Triangle Tri;

inFS.open("rSides.txt");
if(!inFS.is_open())
{
    cout << "Could not open rSides.txt." << endl;
    return 1;
}

while(inFS.good())
{
    cout << "Reading two numbers from rSides.txt" << endl;
    inFS >> a >> b;
    Rect.setHeight(a);
    Rect.setWidth(b);

    if(Rect.checkValidity()==true)
    vRect.push_back(Rect);

    else
    cout << "Invalid Input" << endl;
}

cout << vRect.size() << endl;

for(int i=0;i<vRect.size();i++)
    Rect = vRect.at(i);

    cout << Rect.getArea();
}

【问题讨论】:

  • 这个问题没有多大意义。你好像漏了几个字。

标签: c++ class object vector


【解决方案1】:

事实证明,在我之前的尝试中,我做错了什么。我需要做的就是以我想要的状态调用类:

cout << vRect[i].getArea();

我以为我已经这样做了并且得到了错误,但看起来我只是弄错了。

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2012-09-21
    • 2016-01-23
    • 2014-02-02
    • 2020-12-01
    • 1970-01-01
    • 2021-09-05
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多