我无法访问c ++ vector中的对象。声明向量包含自定义类。
类定义如下:
class SPMgmt {
private:
vector<Part> partList;
vector<Supplier> supplierList;
public:
SPMgmt();
SPMgmt(fstream&, fstream&);
void listPart();
void listSupplier();
void searchPartBySupplierName(string);
void searchSupplierByPartCode(string);
void addNewPart();
};
以下是供应商类:
class Supplier{
public:
// Constructor of an empty Supplier class object
Supplier (){}
// Constructor of a non-empty Supplier object
Supplier (const string& new_name, const string& new_code,
const string& new_phone, const string& new_strt_addr,
const string& new_city_state_zip){
name = new_name;
code = new_code;
phone_number = new_phone;
street_address = new_strt_addr;
city_state_zip = new_city_state_zip;
}
// Copy constructor
Supplier (const Supplier& other){}
// Assignment operator
Supplier& operator= (const Supplier& rightSide){return *this;}
// Destructor -releases any memory allocated to a Supplier object
~Supplier (void){}
// Used to display a Supplier object to standard output
void display (ostream& output) const; // const was added
// Accessor functions:
string get_name ( ) const{return this->name;}
string get_code ( ) const{return this->code;}
string get_phone ( ) const{return this->phone_number;}
string get_street_address ( ) const{return this->street_address;}
string get_city_state_zip ( ) const{return this->city_state_zip;}
// Mutator functions:
void set_name (const string& new_name){this->name = new_name;}
void set_code (const string& new_code){this->code = new_code;}
void set_phone (const string& new_phone){this->phone_number = new_phone;}
void set_street_address (const string& new_street_addr){this->street_address = new_street_addr;}
void set_city_state_zip(const string& new__city_st_zip){this->city_state_zip = new__city_st_zip;}
private:
string name;
string code; // Addd where A is an upper case letter and
// the d's are digits
string phone_number;
string street_address;
string city_state_zip;
};
它的构造函数不能正常工作:
SPMgmt::SPMgmt(fstream& supplierFile, fstream& partFile){
string name, code, phone, streetAddr, cityStateZip;
while(std::getline(supplierFile, name)){
std::getline(supplierFile, code);
std::getline(supplierFile, phone);
std::getline(supplierFile, streetAddr);
std::getline(supplierFile, cityStateZip);
Supplier newSupplier(name, code, phone, streetAddr, cityStateZip);
// get_name() prints out supplier name
cout<<"Name: "<<newSupplier.get_name()<<endl;
// try to put object newSupplier to the vector
supplierList.push_back(newSupplier);
// PROBLEM: get_name() here did not print name. It prints empty string.
cout<<"Name: "<<supplierList[0].get_name()<<endl;
}
我的问题是:为什么存储在向量中的对象没有正确打印其名称?我可以使用get_name()函数在push_back()之前将其名称打印到vector。
答案 0 :(得分:2)
Supplier
类中的复制构造函数和赋值运算符都没有任何用处。
编译器自动生成的复制构造函数和赋值运算符应该适用于您的类,因此您应该删除复制构造函数和赋值运算符,并遵循the rule of zero。