无法访问类中的公共字段C ++

时间:2013-06-25 14:17:34

标签: c++ class field public

我在这里上过这堂课 (这是.h文件)

    #ifndef STORE_H_
    #define STORE_H_

    #include <iostream>
    #include <set>
    #include "list.h"
    #include "Album.h"
    #include "Customer.h"


class Store {

    public:
static const int currentYear = 2013;
Store();
void addAlbum(int barcode, int price, int year, int numPurchased, string title,                             string artist);
void removeAlbum(int barcode);
void addCustomer(int id, string name);
void createNewOrder(int id, int ordNum);
void addToOrder(int ordNum, int barcode);
void removeFromOrder(int ordNum, int barcode);
void payOrder(int ordNum);
string getRecommendations(int numOfRecommendations) const;
string getInventoryReport() const;
string getCustomersReport() const;
string getCustomerReport(int id) const;
string getRevenueReport() const;
~Store();

bool albumsCompare(Album album1, Album album2);
bool customerCompare(Customer customer1, Customer customer2);
std::set<Album> albums;
std::set<Customer> customers;

};

#endif /* STORE_H_ */

我试图访问“专辑”集

std::set<Album> albums;

从这里(.cpp文件)

void addAlbum(int barcode, int price, int year, int numPurchased, string title, string artist) {


    if(barcode <= 0){
        throw INVALID_BARCODE();
    }

    if(price <= 0){
        throw INVALID_PRICE{};
    }

    if(year > Store::currentYear){
        throw INVALID_YEAR();
    }

    if(numPurchased < 0){
        throw INVALID_NUM_PURCHASED();
    }

    if(Album::findBarcode(Store::albums, barcode) != Store::albums.end()){
        throw BARCODE_ALREADY_EXISTS();
    }
}

但我收到错误:无法调用成员函数'std :: set :: iterator Album :: findBarcode(const std :: set&amp;,const int&amp;)'

任何帮助解决这个问题都会非常感激!

这是findBarcode函数

#include "Album.h"




std::set<Album>::iterator Album::findBarcode (std::set<Album>& set,int& barcode){
 Album data = Album();
for (std::set<Album>::iterator i = set.begin(); i != set.end(); i++){
     Album data = *i;
     if(data.barcode == barcode){
            return i;
     }
}
return set.end();

}

2 个答案:

答案 0 :(得分:4)

您正在定义一个非成员函数addAlbum,与您的同名成员函数无关。您需要将成员函数定义放在Store范围:

void Store::addAlbum(int barcode, int price, int year, int numPurchased, string title, string artist)
{//  ^^^^^
  ....
}

答案 1 :(得分:-1)

默认情况下,在c ++中创建类时,所有字段都是privates。 您也可以使用struct key word创建您的类,您的所有字段和方法都将是公共的