对类型的非常量左值引用无法绑定错误

non-const lvalue reference to type cannot bind error

本文关键字:引用 绑定 错误 类型 非常 常量      更新时间:2023-10-16

我试图创建一个非常简单的VCard,但我得到了一个对类型的非常量左值引用,无法在我的main.cpp中绑定错误,无法解决这个问题。问题线路是……

vc->createVCard("JasonSteidorf.vcf",&p1);

//人小时

#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:VCARDn"
       << "VERSION:3.0n"
       << "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:VCARDn";
    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;
}

您尚未将函数createVCardgetCard定义为VCard类的成员函数。

这些都是全局函数。使用范围解析运算符::将它们定义为类的成员函数,如

  void Vcard::createVCard(string fileName,Person &p)
  {
    ....
    ....
  }
  string Vcard::getVCard(Person &p)
  {
    ....
    ....
  }

此外,您的createVCard函数接受对Person的引用,因此您必须将对象传递给人员,而不是指向对象(&p)的指针地址或对象(p)的地址,而是像*p一样通过取消引用来传递对象,因此调用看起来像vc->createVCard("JS.vcf", *p1)