问题
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