C++ 类初始化语法和错误 "does not name a type"

标签 c++

我有一段时间没有接触 C++,希望有人能指出我的类定义中的问题所在。我不断收到一条错误消息“错误:‘IPsource’没有命名类型”。

class AddressPacket {
    std::string address;
    int packets;

    public:
    void initialize(std::string add) {
        address = add;
        packets = 1;
    }
    std::string getAddress() {
        return address;
    }
    int getPackets() {
        return packets;
    }
    bool checkAddress(std::string add) {
        return address == add;
    }
    void addPacket() {
        packets++;
    }
};

class AddressPacketList {
    AddressPacket masterList[100];
    int listCounter;

    public:
    AddressPacketList() { listCounter = 0; }
    void add(std::string add) {
        masterList[listCounter].initialize(add);
        listCounter++;
    }
};

然后在 main 里面我有...

AddressPacketList IPsource();
IPsource.add("Hello");

最佳答案

这并不代表你认为的意思:

AddressPacketList IPsource();

您认为它声明了一个名为 IPsource 且类型为 AddressPacketList 的对象,并使用 AddressPacketList 的默认构造函数对其进行了初始化。

实际上是一个函数声明。您正在声明一个名为 IPsource 的函数,它不接受任何参数并按值返回一个 AddressPacketList 对象。

这个看似离奇的结论是所谓most vexing parse的结果。 .

只需将行更改为:

AddressPacketList IPsource;

关于C++ 类初始化语法和错误 "does not name a type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13401606/

相关文章:

c++ - 如何自定义windows默认右键弹出菜单

C++ 如何在 ofstream 中实际使用 pubsetbuf?

c# - 将 C++ 代码转换为 C# 用于加密算法

c++ - 仅在 Vista 上的子窗口绘画问题

c++ - 在 Windows : Cannot open include file: 'Magick++.h' : No such file or directory 中编译 ZBar 示例时出错

c++ - GCC 中的 PRIuPTR 预处理器错误?

c++ - 如何从基于 QObject 的类方法返回 QList<double> 以便在 Qt 脚本中使用

c++ - g++ : Is there a way to access compile flags inside the code that is being compiled?

c++ - CString 中的转义字符

c++ - Z-Buffer 的高效实现