0

编辑*我很笨...感谢您帮助我解决了这个问题。* 在我的汽车类中,下面的代码不断在 << 运算符上给我一个错误

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;
   }
4

5 回答 5

2

执行此操作的 C++ 方法是为和实现std::ostream&<<运算符。例如,PersonCar

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

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

于 2012-09-01T16:15:09.053 回答
1

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

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

你可能想要

cout << "Driver:" << endl;
driver->print();
于 2012-09-01T16:08:14.940 回答
1

成员函数print返回void。您不能将 avoid插入流中。如果您更改打印函数以获取流引用并添加调用 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;
}
于 2012-09-01T16:25:16.300 回答
0
cout << "Driver: " << driver->print(); 

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

 cout << "Driver: " << driver; 
于 2012-09-01T16:08:16.373 回答
0
const std::string& Person::print() const
{
    return "Name " + name + "\n" + "Age " + age + "\n";    
}
于 2012-09-01T16:55:20.853 回答