我试图创建一个非常简单的 VCard,但我在 main.cpp 中得到一个非常量左值引用类型无法绑定(bind)错误,无法解决这个问题。问题是......
vc->createVCard("JasonSteindorf.vcf", &p1);
//Person.h
#ifndef JASONSTEINDORF_PERSON_H
#define JASONSTEINDORF_PERSON_H
#include <string>
using std::string;
namespace JasonSteindorf{
class Person{
public:
Person();
Person(string firstName,string lastName,string phoneNumber,string email)
: firstName(firstName), lastName(lastName), phoneNumber(phoneNumber), email(email){}
inline string getFirstName(){ return firstName; }
inline string getLastName(){ return lastName; }
inline string getPhoneNumber(){ return phoneNumber; }
inline string getEmail(){ return email; }
private:
string firstName, lastName, phoneNumber, email;
};
}
#endif
//VCard.h
#ifndef JASONSTEINDORF_VCARD_H
#define JASONSTEINDORF_VCARD_H
#include "Person.h"
#include <string>
using std::string;
namespace JasonSteindorf{
class VCard{
public:
void createVCard(string fileName, Person &p);
string getVCard(Person &p);
};
}
#endif
//VCard.cpp
#include "VCard.h"
#include <fstream>
using std::ofstream;
#include <string>
using std::string;
#include <sstream>
#include <iostream>
using std::ostringstream;
using namespace JasonSteindorf;
//Writes the VCard to a file
string getVCard(Person &p){
ostringstream os;
os << "BEGIN:VCARD\n"
<< "VERSION:3.0\n"
<< "N:" << p.getLastName() << ";" << p.getFirstName() << "\n"
<< "FN:" << p.getFirstName() <<" " << p.getLastName() << "\n"
<< "TEL:TYPE=CELL:" << p.getPhoneNumber() << "\n"
<< "EMAIL:" << p.getEmail() << "\n"
<< "URL:" << "http://sorcerer.ucsd.edu/html/people/jason.html" << "\n"
<< "REV:20110719T195243Z" << "\n"
<< "END:VCARD\n";
return os.str();
}
//Returns a string containing the VCard format
void createVCard(string fileName, Person &p){
string vCard = getVCard(p);
ofstream outputFile("/Users/jsteindorf/Desktop/" + fileName);
outputFile << vCard;
}
// main.cpp
#include "Person.h"
#include "VCard.h"
#include <iostream>
using namespace JasonSteindorf;
int main(int argc, const char * argv[])
{
VCard *vc = new VCard();
Person *p1 = new Person ("Jason", "S", "858-555-5555", "js@ucsd.edu");
vc->createVCard("JS.vcf", &p1);
return 0;
}
最佳答案
您还没有将函数 createVCard
和 getCard
定义为 VCard
类的成员函数。
那些是全局函数。使用范围解析运算符 ::
将它们定义为类的成员函数,如
void Vcard::createVCard(string fileName,Person &p)
{
....
....
}
string Vcard::getVCard(Person &p)
{
....
....
}
而且您的 createVCard
函数接受对 Person
的引用,因此您必须将对象传递给 person 而不是指向对象的指针地址 ( &p)
也不是对象的地址 (p)
而是像 *p
那样通过取消引用来传递对象,因此调用看起来像 vc->createVCard("JS.vcf", *p1)
关于c++ - 对类型的非常量左值引用无法绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18063098/