gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:21:54 28 4
gpt4 key购买 nike

编辑* 我很笨...感谢您帮助我解决了这个问题。*在我的 car 类中,下面的代码不断给我一个关于 << operators

的错误
cout << "Driver: " << driver->print(); 
cout << "Owner: " << owner->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++ 方法是实现 std::ostream&<< Person 的运算符和 Car .例如,

#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";

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

关于c++ 指向另一个类错误的指针 "no operator matches these operands.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229302/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com