2

我是 cpp 语言的新手,我的代码有问题,我不知道如何解决,我在这里查看了人们提出的有关此错误的其他一些问题,但没有一个答案真正帮助我解决问题。所以这是我的主要功能:

#include <iostream>
#include "Person.h"
#include <string> 


int main() {
    Person p2();
    Person p1();
    std::cout << p1.toString() << std::endl;
    return 0;
}

这是我的 Person.h 文件:

#ifndef PERSON_H_
#define PERSON_H_
#include <string>
class Person {
private:
    int age;
    std::string name;
    int numOfKids;
public:
    Person() {
        this->age = 0;
        this->name = "bob";
        this->numOfKids = 5;
    }
    Person(int agee, std::string namee, int numof);
    ~Person();
    std::string toString();


};

#endif // PERSON_H_

在主函数中,它标记p1.toString()并说“表达式必须具有类类型”,我不知道该怎么做,我尝试了很多东西,但都没有奏效。

4

2 回答 2

1

您编写的此类陈述可能具有模棱两可的含义: Person p2();

  1. (你想要什么)一个类型为 Person 且默认构造的变量 p2 。
  2. (编译器认为)一个函数声明 p2 返回一个 Persion 对象。

删除括号或使用'{}'(c ++ 11)应该清楚:

Person p1{};
Person p2;
于 2019-11-20T07:28:13.850 回答
0

各种纠正点:

Person(int agee, std::string namee, int numof);
~Person();
std::string toString();

这三个只是声明,没有定义。这将导致来自编译器的未解析的外部符号错误消息。更正 p1 和 p2 的变量声明。使用此剪辑作为方向:

#include <iostream>

class Person
{
private:
    int age;
    std::string name;
    int numOfKids;
public:
    Person()
    {
        this->age = 0;
        this->name = "bob";
        this->numOfKids = 5;
    }

    Person(int agee, std::string namee, int numof)
    {
        // ToDo
    }

    ~Person()
    {
        // ToDo
    }

    std::string toString()
    {
        // ToDo
        return "";
    }
};

int main()
{
    Person p2;
    Person p1;
    std::cout << p1.toString() << std::endl;
    return 0;
}
于 2019-11-20T07:39:09.360 回答