c++ 指向另一个类 bug "no operator matches these operands."的指针

c++ Pointer to another class bug "no operator matches these operands."

本文关键字:these matches operands 指针 operator no 另一个 bug c++      更新时间:2023-10-16

编辑*我很笨。。。谢谢你帮我解决了这个问题。*在我的汽车类中,下面的代码在<lt;操作员

cout << "Driver: " << driver->print(); 
cout << "Owner: " << owner->print();

错误显示"没有一个运算符匹配这些操作数。"这是我的家庭作业,所以我确实需要从驱动程序调用print函数。在主要功能中,我还没有真正设置驾驶员或车主,但我认为这应该无关紧要。提前谢谢。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person
{
public:
Person(string _name,int _age)
{
    _name = name;
    _age = age;
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
}
string getName()
{
    return name;
}
int getAge()
{
    return age;
}
int incrementAge()
{
    age +=1;
    return age;
}
void print()
{
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
}

private:
string name;
int age;
};
class Car
{
public:
Car (string m)
{
    model = m;
}
void setDriver(Person *d)
{
    *driver = *d;
}
void setOwner(Person *o)
{
    *owner = *o;
}
void print()
{
    cout << "Model: " << model << endl;
    cout << "Driver: " << driver->print();
    cout << "Owner: " << owner->print();
}


private:
string model;
Person *owner;
Person *driver;

};
int main()
{
vector<Person*>people;
vector<Car*>cars;
string name = "";
int age = 0;
string model = 0;
int sentValue = 0;
while (sentValue != -1)
{
    cout << "Enter name: ";
    cin >> name;
    cout << "Enter age: ";
    cin >> age;

    people.push_back(new Person(name, age));
    cout << "Enter car model: ";
    cin >> model;
            cars.push_back(new Car(model));
    cout << "Press -1 to stop, or 1 to enter info for others: ";
    cin >> sentValue;
}



//display car model, 
//owner’s name and age,
//and driver’s name and age.
system("pause");
return 0;
   }

实现这一点的C++方法是为PersonCar实现std::ostream&<<运算符。例如,

#include <iostream>
std::ostream& operator<<(std::ostream& o, const Person& p) {
  return o << "Name: " << p.getName() << " Age: " << p.getAge();
}

然后这样使用:

Person p("Bob", 23);
std::cout << p << "n";

顺便说一句,我不认为你真的需要在代码中使用所有这些指针。

您的print()函数已经将输出发送到cout,因此无需再次尝试将其发送到那里。代替

cout << "Driver: " << driver->print(); 

你可能想要

cout << "Driver:" << endl;
driver->print();

成员函数print返回void。不能将void插入流中。如果您更改print函数以获取流引用,并添加重载的调用print的运算符,则可以将对象本身插入流中;那会更地道。

template <class Elem, class Traits>
void Car::print(std::ostream<Elem, Traits>& out) {
    out << "Model: " << model << 'n';
    out << "Driver: " << *driver;
    out << "Owner: " << *owner;
}
template <class Elem, class Traits>
std::ostream<Elem, Traits>& out, const Car& car) {
    return out << car;
}
cout << "Driver: " << driver->print(); 

您的<<正在等待适当的对象进行处理。这是你的问题。与其实现print(),不如通过实现operator<<(std::ostream&, const Person&);来重载运算符,并让C++来完成其余的工作

 cout << "Driver: " << driver; 
const std::string& Person::print() const
{
    return "Name " + name + "n" + "Age " + age + "n";    
}