Friend Function, expected Primary Expression before . token

偶尔善良 提交于 2021-01-29 20:33:55

问题


So there are two classes in separate header files

Customer. h

using namespace std;
#include <iostream>

class Customer{
    friend void Display();
private:
    int number, zipCode;
public:
    Customer(int N, int Z){
    number = N;
    zipCode = Z;
    }
};

City. h using namespace std; #include #include "Customer.h"

class City{
    friend void Display();
private:
    int zipCode;
    string city, state;
public:
    City(int Z, string C, string S){
        zipCode = Z;
        city = C;
        state = S;
    }
};

my main.cpp is as follows

#include "City.h"
#include "Customer.h"

void Display(){
        cout<<"Identification Number: "<<Customer.number<<endl
                <<"Zip Code: "<<Customer.zipCode<<endl
                <<"City: "<<City.city<<endl
                <<"State: "<<City.state<<endl;
    }


int main() {
    Customer A(1222422, 44150);
    City B(44150, "Woklahoma", "Kansas");

    Display();

}

I'm good with the basics of c++ but this is where I Don't understand, so my specific question is.... Why for the four lines of my Display function does the compiler tell me "error: expected primary-expression before ‘.’ token"

Thanks in advance, Macaire


回答1:


Customer is a type. You need an object of that type to access it's number member (and the same for the rest of the lines).

You probably meant to take a Customer and City as arguments to Display:

void Display(Customer customer, City city){
    cout<<"Identification Number: "<<customer.number<<endl
            <<"Zip Code: "<<customer.zipCode<<endl
            <<"City: "<<city.city<<endl
            <<"State: "<<city.state<<endl;
}

Then pass your Customer and City objects to that function:

Display(A, B);



回答2:


You are attempting to access data members from a class name

Customer.number

You cannot do that. You need a Customer instance:

Customer c;
std::cout << c.number;

You probably want to change Display() to

void Display(const Customer& c);

then use it like this:

Customer A(1222422, 44150);
Display(A);

and similarly for City.



来源:https://stackoverflow.com/questions/15326648/friend-function-expected-primary-expression-before-token

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!