我知道我的消息格式不正確,但是我是新來的,所以請幫助我。 我有兩個班:父親和兒子。在兒子我有一個int和一個字符串。 在父親,我有一個兒子對象的向量。 如何訪問由整數和/或由字符串組成的部分構成的矢量部分? 非常感謝!在C++中拆分對象向量
CLASS SON.H
#ifndef SON_H
#define SON_H
#include <iostream>
using namespace std;
class Son
{
public:
Son() {}
Son(int first, string second);
virtual ~Son();
int getFirst() const;
string getSecond() const;
private:
int _first_parameter;
string _second_parameter;
};
#endif // SON_H
CLASS SON.CPP
#include "son.h"
Son::Son(int first, string second)
{
_first_parameter=first;
_second_parameter=second;
}
Son::~Son()
{
//dtor
}
int Son::getFirst() const
{
return _first_parameter;
}
string Son::getSecond() const
{
return _second_parameter;
}
CLASS FATHER.H
#ifndef FATHER_H
#define FATHER_H
#include <vector>
#include "son.h"
class Father
{
public:
Father() {}
virtual ~Father();
void filling();
private:
vector<Son> _access_vector;
void _printIntegers(vector<int> v);
void _printStrings(vector<string> v);
};
#endif // FATHER_H
個
CLASS FATHER.CPP
#include "father.h"
Father::~Father()
{
//dtor
}
void Father::filling()
{
int temp_first_param;
string temp_second_param;
cout<<"Insert integer: "<<endl;
cin>>temp_first_param;
cout<<"Insert text"<<endl;
cin>>temp_second_param;
_access_vector.push_back(Son(temp_first_param, temp_second_param));
_printIntegers(_access_vector.getFirst()); /// Here I want to take just the vector of integers
_printStrings(_access_vector.getSecond()); /// Here I want to take just the vector of strings
}
void Father::_printIntegers(vector<int> v)
{
for(unsigned i=0; i<v.size(); ++i)
cout<<v[i]<<endl;
}
void Father::_printStrings(vector<string> v)
{
for(unsigned i=0; i<v.size(); ++i)
{
cout<<v[i]<<endl;
}
}
編譯器錯誤:
||=== Build: Debug in Vector_access_experiment (compiler: GNU GCC Compiler) ===| C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp||In member function 'void Father::filling()':| C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|17|error: 'class std::vector' has no member named 'getFirst'| C:\Users\Alessandro\Documents\CodeBlocks\Vector_access_experiment\src\father.cpp|18|error: 'class std::vector' has no member named 'getSecond'| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
回顧* [*'std :: vector' **](http://en.cppreference.com/w/cpp/container/vector)提供的*與你想要做什麼與它一起,這些錯誤非常有意義。如果不是自我解釋,這些錯誤就不算什麼; 'std :: vector'中沒有'getFirst'和'getSecond'方法。 – WhozCraig
沒有「只是由整數組成的矢量的一部分」,所以你不能訪問任何這樣的東西。 –
'getFirst'和'getSecond'是'Son'類的方法,而不是'std :: vector'類的方法。在嘗試訪問其方法之前,您必須從矢量中獲取對象。 –