了解函数错误的歧义新声明

Understanding the ambiguating new declaration of function error

本文关键字:声明 新声明 歧义 函数 错误 了解      更新时间:2023-10-16

我不明白这个错误以下是在线查看代码的链接:

https://onlinegdb.com/rkirYvU_M

我正在尝试将驱动程序、所有者和模型的名称添加到向量中,我们需要使用指针和文件。

这是我的主要文件:

#include "person.h"
#include "car.h"
#include <iostream>
#include <vector> 
std::vector <Person*>people;
std::vector <Car*> cars;
int main()
{
    bool done = false;
    Person person;
    while(! done)
    {
        std::cout << "n Please enter the owners ";
        Person*prompt_info();
        std::cout << "n Please enter the drivers ";
        Car*prompt_info();
        Car*set();
        Car*print();
    }
    return 0;
}

这是 person.h 文件:

#ifndef PERSON_H
#define PERSON_H
#include <string>
#include <iostream>
//using namespace std;

class Person
{
public:
    Person();
    std::string get_name();
    int get_age();
    void prompt_info();
private:
    std::string name;
    int age;

};
#endif 

下面是 person.c++ 文件:

#include "person.h"
Person::Person()
{
}

void Person::prompt_info()
{
    std::cout << " name: ";
    std::cin >> name;
    std::cout << "enter their age: ";
    std::cin >> age;
}
std::string Person::get_name()
{
    return name;
}

int Person::get_age()
{
    return age;
}

这是car.h文件:

#ifndef CAR_H
#define CAR_H
#include <string>
#include <iostream>
#include "person.h"    
using namespace std;
class Car
{    
public:
    Car();
    std::string get_model();
    Person* get_owner();
    Person* get_driver();
    void print();
    void set(Person _owner,Person get_driver);
    void prompt_info();
private:
    std::string model;
    Person*  owner;
    Person* driver;
};
#endif 

我正在尝试理解此错误。

main.cpp:23:25: error: ambiguating new declaration of 'Car* prompt_info()'
     Car*prompt_info();
                     ^

您似乎将函数声明与成员函数混淆了。只需在堆栈上声明一个Person对象,并通过它的对象调用该方法。对Car对象执行相同的操作。您可以像这样使用对象。

while(! done)
{
    Person person;  ///< Person object named 'person'
    Car car;        ///< Car object named 'car'
    std::cout << "n Please enter the owners ";
    person.prompt_info();
    std::cout << "n Please enter the drivers ";
    car.prompt_info();
    car.set();
    car.print();
    // TODO do something with your objects (store to vector?)
    // next time through the loop your person and car will
    // get initialized all over again
}
return 0;

如果要稍后使用临时对象,则必须在临时对象超出范围之前存储它们。